Execute task on current thread

后端 未结 5 1023
灰色年华
灰色年华 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:03

    Since you mention testing, you might prefer using a TaskCompletionSource since it also lets you set an exception or set the task as cancelled (works in .Net 4 and 4.5):

    Return a completed task with a result:

    var tcs = new TaskCompletionSource();
    tcs.SetResult(func());
    return tcs.Task;
    

    Return a faulted task:

    var tcs = new TaskCompletionSource();
    tcs.SetException(new InvalidOperationException());
    return tcs.Task;
    

    Return a canceled task:

    var tcs = new TaskCompletionSource();
    tcs.SetCanceled();
    return tcs.Task;
    

提交回复
热议问题