Reputation: 263
I am quite new to this whole threading thing, so hopefully someone can enlighten me.
I have a WPF UI from which I start a DLL on the click of a button. When the button is clicked, it runs the dll asynchronously so that the user can still "navigate" the UI while the dll is performing its work:
await Task.Factory.StartNew(new Action(() => strTime =
StartSync.Start(strPathFile,
licManager.idCmsMediator)));
this worked very well until I had to run this Task on STA mode to open windows in the dll. So I changed this line using the method described in 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);
but now when I run the dll by clicking the button, I cannot navigate the UI anymore ! Like it is NOT running asynchronously anymore !? How can I start the task in STA mode but still be able to navigate the UI ?
Thanks in advance
Upvotes: 4
Views: 1471
Reputation: 149598
but now when I run the dll by clicking the button, I cannot navigate the UI
Task != Thread
. A task may or may not use a thread to do it's work.
When you use:
var scheduler = TaskScheduler.FromCurrentSynchronizationContext();
You're telling the task factory to execute the given delegate on the current captured synchronization context, which is your UI synchronization context. When you do that, it will execute this on the UI message loop.
this worked very well until I had to run this Task on STA mode to open windows in the dll
Opening a window should be done on the UI thread, hence why it's complaining. What you can do is defer the execution of the CPU bound work the a background thread, and once you need to manipulate the UI, marshal the work back:
// 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.
Upvotes: 3