Is it possible to force a task to execute synchronously, on the current thread?
That is, is it possible, by e.g. passing some parameter to StartNew()
, to ma
Yes, you can pretty much do that using custom task schedulers.
internal class MyScheduler : TaskScheduler
{
protected override IEnumerable GetScheduledTasks()
{
return Enumerable.Empty();
}
protected override void QueueTask(Task task)
{
base.TryExecuteTask(task);
}
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
base.TryExecuteTask(task);
return true;
}
}
static void Main(string[] args)
{
Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " Main");
Task.Factory.StartNew(() => ThisShouldBeExecutedSynchronously(), CancellationToken.None, TaskCreationOptions.None, new MyScheduler());
}