How to run a Task on a custom TaskScheduler using await?

后端 未结 5 1855
暖寄归人
暖寄归人 2020-11-28 05:24

I have some methods returning Task on which I can await at will. I\'d like to have those Tasks executed on a custom TaskScheduler

5条回答
  •  借酒劲吻你
    2020-11-28 05:47

    I think what you really want is to do a Task.Run, but with a custom scheduler. StartNew doesn't work intuitively with asynchronous methods; Stephen Toub has a great blog post about the differences between Task.Run and TaskFactory.StartNew.

    So, to create your own custom Run, you can do something like this:

    private static readonly TaskFactory myTaskFactory = new TaskFactory(
        CancellationToken.None, TaskCreationOptions.DenyChildAttach,
        TaskContinuationOptions.None, new MyTaskScheduler());
    private static Task RunOnMyScheduler(Func func)
    {
      return myTaskFactory.StartNew(func).Unwrap();
    }
    private static Task RunOnMyScheduler(Func> func)
    {
      return myTaskFactory.StartNew(func).Unwrap();
    }
    private static Task RunOnMyScheduler(Action func)
    {
      return myTaskFactory.StartNew(func);
    }
    private static Task RunOnMyScheduler(Func func)
    {
      return myTaskFactory.StartNew(func);
    }
    

    Then you can execute synchronous or asynchronous methods on your custom scheduler.

提交回复
热议问题