Execute task on current thread

后端 未结 5 1022
灰色年华
灰色年华 2021-02-05 05:35

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

5条回答
  •  一生所求
    2021-02-05 06:01

    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());
    }
    

提交回复
热议问题