@NDJ 发布的内容是正确的,我做了一个简单的例子来展示发生了什么。
首先,方法:
private static void TaskGestioneCartelle()
{
Task.Factory.StartNew(() => GeneraListaCartelle())
.ContinueWith(t => GeneraListaCartelleCompletata()
, CancellationToken.None
, TaskContinuationOptions.None
, TaskScheduler.FromCurrentSynchronizationContext());
}
private static void GeneraListaCartelle()
{
//No sleep could block the thread UI because the task is being executed on a different Thread
Debug.WriteLine("GeneraListaCartelle " + Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(4000);
mainForm.Invoke(new Action(() => bla.Text = "uno due tre, Genera Lista!"));
}
private static void GeneraListaCartelleCompletata()
{
//This is begin executed on the UI thread
Debug.WriteLine("GeneraListaCartelleCompletata " + Thread.CurrentThread.ManagedThreadId);
Task.Factory.StartNew(() => CopiaCartelle())
.ContinueWith(t => CopiaCartelleCompletato()
, CancellationToken.None
, TaskContinuationOptions.None
, TaskScheduler.FromCurrentSynchronizationContext());
}
private static void CopiaCartelle()
{
//This is begin executed on the UI thread (doesn't even show in the form 'cause the thread is blocked)
Debug.WriteLine("CopiaCartelle " + Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(4000);
mainForm.Invoke(new Action(() => bla.Text = "Copia Cartelle \\o"));
}
private static void CopiaCartelleCompletato()
{
//This is begin executed on the UI thread
Debug.WriteLine("CopiaCartelleCompletato " + Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(4000);
mainForm.Invoke(new Action(() => bla.Text = "Completato!"));
//Stops blocking the UI thread
}
现在表单和组件
static Label bla = new Label()
{
Text = "Mama Mia, Gestione Cartelle!",
Left = 100,
Top = 100,
Width=300
};
static Label hangOn = new Label()
{
Text="Hang loose"
};
static Form mainForm = new Form()
{
Width = 600,
Height = 600
};
[STAThread]
static void Main(string[] args)
{
mainForm.Controls.Add(bla);
mainForm.Controls.Add(hangOn);
mainForm.MouseMove += (o, e) => { hangOn.Left = e.X; hangOn.Top = e.Y; };
Debug.WriteLine("UI Thread: "+ Thread.CurrentThread.ManagedThreadId);
TaskGestioneCartelle();
Application.Run(mainForm);
}
首先,运行应用程序并继续移动鼠标。Hang Loose
当Label 停止跟随您的鼠标时,您会注意到 UI 线程被阻止。
现在,如果你Output
从 Debug 中检查,你会看到类似这样的东西:
UI Thread: 10
GeneraListaCartelle 6
GeneraListaCartelleCompletata 10
CopiaCartelle 10
CopiaCartelleCompletato 10
看?它使用 UI 线程来运行您的任务,从而挂起您的 UI。
现在,TaskScheduler.FormCurrentSynchronizationContext()
改为TaskScheduler.Default
多田:
UI Thread: 8
GeneraListaCartelle 9
GeneraListaCartelleCompletata 10
CopiaCartelle 10
CopiaCartelleCompletato 11
在注释中,看到我mainForm.Invoke
用来调用要在 中执行的操作UI Thread
,例如更改标签文本。
如果您还有任何疑问,请随时发表评论。