同步任务取消

时间:2013-10-18 13:45:03

标签: c# c#-4.0

我正在寻找一种同步任务取消的方法。我有这样的任务:

public Task AddAsync(CancellationToken cancellationToken)
{
    Task result = Task.Factory.StartNew(() =>
    {
        // So wait forever
        var wait = new ManualResetEvent(false);
        var waitIndex = WaitHandle.WaitAny(new[] { wait,
            cancellationToken.WaitHandle});

        switch (waitIndex)
        {
            case 0:
                Debug.WriteLine("Everything fine");
                break;
            case 1:
                Debug.WriteLine("Cancelled");
                Thread.Sleep(5000);
                cancellationToken.ThrowIfCancellationRequested();
                break;
        }
        return;
    }, cancellationToken);

    return result;
}

异步方法将像这样调用:

var ts = new CancellationTokenSource();
var t = AddAsync(ts.Token);
if (!t.Wait(TimeSpan.FromSeconds(5)))
{
    ts.Cancel();
}

所以在超时后我打电话取消,但任务需要一些时间才能取消。那么如何进行同步取消呼叫呢?

0 个答案:

没有答案