gpt4 book ai didi

c# - 任务 T.IsCancelled = false;我怎样才能做到这一点?

转载 作者:太空宇宙 更新时间:2023-11-03 21:16:14 25 4
gpt4 key购买 nike

我有这个异步方法:

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 给出的答案让我得出了这个结论......

最佳答案

来自 the documentation

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.

关于c# - 任务 T.IsCancelled = false;我怎样才能做到这一点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34136153/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com