0

I am trying to create a Task with the TPL. eg:

Task.Factory.StartNew(() => DoSomething());

This works fine, but now I want to start it on the gui thread.

I can cache the gui scheduler with:

_uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();

but I can't see how to start a new task using this scheduler. All the examples I can find use Task.ContinueWith() to schedule a second task using _uiScheduler once the initial task has finished, but I want to create the initial task using this scheduler.

Cheers

GazTheDestroyer
  • 20,722
  • 9
  • 70
  • 103

3 Answers3

3

There is a huge number of overloads of StartNew. One of them accepts a scheduler. Simply pass None for the other parameters:

Task.Factory.StartNew(() => DoSomething(), CancellationToken.None,
                      TaskCreationOptions.None, _uiScheduler);
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
2

Simple - there are overloads (such as this one) of TaskFactory.StartNew which take a scheduler as one of the parameters.

Task.Factory.StartNew(() => DoSomething(), CancellationToken.None,
                      TaskCreationOptions.None, _uiScheduler);
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

Try this:

TaskFactory factory = new TaskFactory(TaskScheduler.FromCurrentSynchronizationContext());
factory.StartNew(() => DoSomething());
Hamlet Hakobyan
  • 32,965
  • 6
  • 52
  • 68