Let's say I have a FormWithLabel (just form with a label to show status of current long-term operation) which I show in case of some "heavy" tasks running in my main application form. For this purpose I have static variable:
public static FormWithLabel loadingForm = null;
I case of "heavy" tasks I create FormWithLabel in separate thread an show it until log operation ends. When I use Thread - it's ok:
Thread loadingFormThread = new Thread(new ThreadStart(() =>
{
loadingForm = new FormWithLabel();
loadingForm.ShowDialog();
}
));
loadingFormThread.SetApartmentState(ApartmentState.STA);
loadingFormThread.Start();
...
//some "heavy" work which is done separate thread and updates some visual data in main UI via Invoke()
...
if (loadingForm != null)
{
loadingForm.Dispose();
loadingForm = null;
}
But when I use Task instead of Thread
new Task(() =>
{
loadingForm = new FormWithLabel();
loadingForm.ShowDialog();
}).Start();
...
//some "heavy" work which is done separate thread and updates some visual data in main UI via Invoke()
...
if (loadingForm != null)
{
loadingForm.Dispose();
loadingForm = null;
}
loadingForm is NULL at the end of "heavy" work - so .Dispose() is never called.
What is the difference between Thread and Task?
Why my static variable remain global in first case and look like it's local for Taks's thread in second case?
FormWithLabelfrom main UI thread (no task or thread) and then use task or thread to do the heavy work and may be useInvoketo update UI from your heavy work.