簡體   English   中英

如何在 C# 中停止異步方法的執行?

[英]how to stop async method execution in c#?

我正在使用異步方法。 當計時器引發超時事件時,如何停止其執行?

我的代碼:

public async Task<object> Method()
{
    cts = new CancellationTokenSource();
    try
    {
        timer = new System.Timers.Timer(3000);
        timer.Start();
        timer.Elapsed += (sender, e) =>
        {
            try
            {
                timer_Elapsed(sender, e, cts.Token, thread);
            }
            catch (OperationCanceledException)
            {
                return;
            }
            catch (Exception ex)
            {
                return;
            }
        };
        await methodAsync(cts.Token);
        return "message";
    }
    catch (OperationCanceledException)
    {
        return "cancelled";
    }
    catch (Exception ex)
    {
        return ex.Message;
    }
}

// Async Call
public async Task<object> methodAsync(CancellationToken ct)
{
    try
    {
        pdfDocument = htmlConverter.Convert("path", "");
    }
    catch(Exception ex)
    {
        return x.Message;
    }
}

// Timer event
void timer_Elapsed(object sender, ElapsedEventArgs e, CancellationToken ct)
{ 
    cts.Cancel();
    ct.ThrowIfCancellationRequested();
}

以下是取消任務的工作原理:

public async Task<object> Method()
{
    cts = new CancellationTokenSource();
    await methodAsync(cts.Token);
    return "message";
}

public Task<object> methodAsync(CancellationToken ct)
{
    for (var i = 0; i < 1000000; i++)
    {
        if (ct.IsCancellationRequested)
        {
            break;
        }
        //Do a small part of the overall task based on `i`
    }
    return result;
}

您必須響應ct.IsCancellationRequested屬性的ct.IsCancellationRequested才能知道何時取消任務。 一個線程/任務沒有安全的方法來取消另一個線程/任務。

在您的情況下,您似乎正在嘗試調用一個不知道CancellationToken方法,因此您無法安全地取消此任務。 您必須讓線程/任務繼續完成。

我認為您可以嘗試提及何時取消它。 就像是

cts.CancelAfter(TimeSpan.FromMilliseconds(5000));

此外,您需要在被調用的方法中使用取消標記。 那時你就會知道什么時候取消。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM