Task.StartNew() 在 STA 模式下的工作方式不同?
Task.StartNew() works differently on STA mode?
我对这整个线程的事情很陌生,所以希望有人能启发我。
我有一个 WPF UI,我通过单击按钮从中启动一个 DLL。单击按钮时,它会异步 运行s dll,以便用户在 dll 执行其工作时仍然可以 "navigate" UI:
await Task.Factory.StartNew(new Action(() => strTime =
StartSync.Start(strPathFile,
licManager.idCmsMediator)));
在我不得不 运行 在 STA 模式下执行此任务以在 dll 中打开 windows 之前,它工作得很好。所以我使用 this post 中描述的方法更改了这一行:
var scheduler = TaskScheduler.FromCurrentSynchronizationContext();
await Task.Factory.StartNew(new Action(() => strTime =
StartSync.Start(strPathFile,
licManager.idCmsMediator)),
System.Threading.CancellationToken.None,
TaskCreationOptions.None, scheduler);
但是现在当我通过单击按钮 运行 dll 时,我无法再导航 UI 了!好像它不再 运行ning 异步了!?如何在 STA 模式下启动任务但仍然能够导航 UI ?
提前致谢
but now when I run the dll by clicking the button, I cannot navigate
the UI
Task != Thread
。任务可能会也可能不会使用线程来完成它的工作。
当您使用:
var scheduler = TaskScheduler.FromCurrentSynchronizationContext();
您要告诉任务工厂在当前捕获的同步上下文(即您的 UI 同步上下文)上执行给定的委托。当您这样做时,它将在 UI 消息循环中执行。
this worked very well until I had to run this Task on STA mode to open
windows in the dll
打开 window 应该在 UI 线程上完成,这就是它抱怨的原因。您可以做的是将 CPU 绑定工作的执行推迟到后台线程,一旦您需要操作 UI,将工作编组回去:
// Start CPU bound work on a background thread
await Task.Run(() => strTime = StartSync.DoCpuWork(strPathFile,
licManager.idCmsMediator)));
// We're done awaiting, back onto the UI thread, Update window.
我对这整个线程的事情很陌生,所以希望有人能启发我。
我有一个 WPF UI,我通过单击按钮从中启动一个 DLL。单击按钮时,它会异步 运行s dll,以便用户在 dll 执行其工作时仍然可以 "navigate" UI:
await Task.Factory.StartNew(new Action(() => strTime =
StartSync.Start(strPathFile,
licManager.idCmsMediator)));
在我不得不 运行 在 STA 模式下执行此任务以在 dll 中打开 windows 之前,它工作得很好。所以我使用 this post 中描述的方法更改了这一行:
var scheduler = TaskScheduler.FromCurrentSynchronizationContext();
await Task.Factory.StartNew(new Action(() => strTime =
StartSync.Start(strPathFile,
licManager.idCmsMediator)),
System.Threading.CancellationToken.None,
TaskCreationOptions.None, scheduler);
但是现在当我通过单击按钮 运行 dll 时,我无法再导航 UI 了!好像它不再 运行ning 异步了!?如何在 STA 模式下启动任务但仍然能够导航 UI ?
提前致谢
but now when I run the dll by clicking the button, I cannot navigate the UI
Task != Thread
。任务可能会也可能不会使用线程来完成它的工作。
当您使用:
var scheduler = TaskScheduler.FromCurrentSynchronizationContext();
您要告诉任务工厂在当前捕获的同步上下文(即您的 UI 同步上下文)上执行给定的委托。当您这样做时,它将在 UI 消息循环中执行。
this worked very well until I had to run this Task on STA mode to open windows in the dll
打开 window 应该在 UI 线程上完成,这就是它抱怨的原因。您可以做的是将 CPU 绑定工作的执行推迟到后台线程,一旦您需要操作 UI,将工作编组回去:
// Start CPU bound work on a background thread
await Task.Run(() => strTime = StartSync.DoCpuWork(strPathFile,
licManager.idCmsMediator)));
// We're done awaiting, back onto the UI thread, Update window.