簡體   English   中英

如何通過超時取消暫停的方法?

[英]How to cancel suspended method by timeout?

我知道如何取消通過超時執行的方法。 我的意思是Task-Wait-Timeout-CancellationToken技巧。 即方法包裝在Task中。 此技術效果很好。 例如:

private void TestConnectMethod()
{
    int QueryTimeOut = 1000; //in ms

    _txtError.Visibility = Visibility.Hidden;

    var cancellationTokenSource = new CancellationTokenSource();
    var token = cancellationTokenSource.Token;

    var task = Task.Factory.StartNew(() =>
    {
        while (true)
        {
            if (token.IsCancellationRequested)
               token.ThrowIfCancellationRequested();

            Debug.WriteLine("Iteration" + DateTime.Now);
        }

    }, token).ContinueWith(t =>
    {

    });

    var wres = task.Wait(QueryTimeOut);

    if (!wres)
    {
        cancellationTokenSource.Cancel();
        _txtError.Text = "Timeout!";
    }
    else
    {
        _txtError.Text = "All is ОК";
    }
}

任務將被成功取消。 但是,如果Task看起來像這樣:

var task = Task.Factory.StartNew(() =>
    {
        // This is a server method that can be suspended
        ArchiveServiceClient.Instance.Authenticate()
    }, token).ContinueWith(t =>
    {

    });

如果服務器不響應,則ArchiveServiceClient.Instance.Authenticate()方法可以掛起應用程序。 現在,我不能寫

if (token.IsCancellationRequested)
    token.ThrowIfCancellationRequested();

因為這些字符串將無用。 如何停止使用掛起方法執行Task 可能嗎?

通常,您不能取消任何代碼的執行。

您首先發布的示例假設該代碼支持優美的取消模式。 當然,並非每個方法/類/庫都如此, ArchiveServiceClient.Instance.Authenticate演示了這一點。

Tread.Abort有一些技巧,但您應避免使用它們,因為它們有害Tread.Abort ,而不是有用,並且您不能以這種方式取消非托管代碼)。

從.NET應用程序中取消某些內容的唯一可靠方法是將這些內容放在單獨的進程中,並在超時時終止該進程。 當然,與正常取消相比,這需要更復雜的方法。

暫無
暫無

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

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