我有这个异步方法:
private static async Task Initializ( ) { /*Do Stuff Here*/ }
我希望能够监控调用此函数所产生的任务:
Task T = Class.Initialize( );
if (T.IsCancelled){ /*Do Stuff Here*/ }
我有一个 CancellationTokenSource。
我怎样才能使 T(或函数 Initialize)利用该源 token ,这样如果它被取消,T.IsCancelled 将是真的吗?
编辑
我不确定,但我认为我的问题的答案在于使用 TaskCompletionSource 对象。 Mike 给出的答案让我得出了这个结论......
请您参考如下方法:
A Task will complete in the TaskStatus.Canceled state under any of the following conditions:
Its CancellationToken was marked for cancellation before the task started executing,
The task acknowledged the cancellation request on its already signaled CancellationToken by throwing an OperationCanceledException that bears the same CancellationToken.
The task acknowledged the cancellation request on its already signaled CancellationToken by calling the ThrowIfCancellationRequested method on the CancellationToken.
