Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Task.Factory.StartNew() runs on wrong thread if Modal dialog opened

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.

like image 454
Akuma Avatar asked Nov 11 '11 16:11

Akuma


People also ask

What is the difference between task run () and TaskFactory StartNew () methods?

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!

What does task factory StartNew do?

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.

What is the use of task factory in C#?

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.


1 Answers

You are on the right track. In COM, when you are running in a single-threaded apartment, it is just all the same thread...

like image 112
Aliostad Avatar answered Oct 02 '22 04:10

Aliostad