Can anyone explain why, if a C++ application runs a .NET UI component (all on the main thread) which in turn spawns a modal .NET dialog and then tries to use TaskScheduler.FromCurrentSynchronizationContext();
in a Task.Factory.StartNew
call the task is run on a worker thread? This doesn't happen if I do not show the dialog or if I store off the context before showing the dialog.
I tried to create a dummy program to show it but failed, I think it's likely related to having a main process which is COM.
Any ideas?
Ok my code looks like this
private void RunStateMachine(IQ4UpgraderState State)
{
_State = State;
Task.Factory.StartNew(() => StateMachine(), _TokenSource.Token, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
}
private void StateMachine()
{
switch (_State)
{
//Some Code
}
}
When the Task is started the current context is the Main Thread but when the StateMachine call runs it is on a worker thread if and only if I have opened a modal dialogue prior to running this code. The context returned by TaskScheduler.FromCurrentSynchronizationContext() appears to be correct at the point of starting my task. I have even compared what is returned in both situations and there appears to be no difference.
Run(action) internally uses the default TaskScheduler , which means it always offloads a task to the thread pool. StartNew(action) , on the other hand, uses the scheduler of the current thread which may not use thread pool at all!
StartNew(Action<Object>, Object, CancellationToken, TaskCreationOptions, TaskScheduler) Creates and starts a task for the specified action delegate, state, cancellation token, creation options and task scheduler.
The TaskFactory class, which creates Task and Task<TResult> objects. You can call the overloads of this method to create and execute a task that requires non-default arguments.
You are on the right track. In COM, when you are running in a single-threaded apartment, it is just all the same thread...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With