简体   繁体   English

如何避免扩展方法中的TaskCanceledException?

[英]How can I avoid a TaskCanceledException in an extension method?

I'm starting a Process and wanting to call WaitForExit in an async way. 我正在启动一个Process并希望以异步方式调用WaitForExit Using another Stack Overflow answer as a template, I have this extension method to do it: 使用另一个Stack Overflow答案作为模板,我可以使用以下扩展方法来做到这一点:

public static class ProcessExtensions
{
    public static Task WaitForExitAsync(this Process process, int milliseconds)
    {
        var tcs = new TaskCompletionSource<object>();
        process.EnableRaisingEvents = true;
        process.Exited += (sender, args) => tcs.TrySetResult(null);

        var cts = new CancellationTokenSource(milliseconds);
        cts.Token.Register(() => tcs.TrySetCanceled());

        return tcs.Task;
    }
}

That way I can call await process.WaitForExitAsync(1000) to accomplish what I want. 这样,我可以调用await process.WaitForExitAsync(1000)完成我想要的工作。 If the task exits before the timeout happens, then it's all fine. 如果任务在超时发生之前退出,那么一切都很好。 But the problem I'm running into is that when the timeout period is hit, it just throws a TaskCanceledException . 但是我遇到的问题是,当达到超时期限时,它只会引发TaskCanceledException The whole point of the extension method is to handle things gracefully in one line. 扩展方法的重点是在一行中优雅地处理事物。 I shouldn't need to wrap this call in a try catch when I just want it to continue either way. 当我只希望以任何一种方式继续进行调用时,都不需要将该调用包装在try catch中。 How do I accomplish this? 我该如何完成?

Forgive me for the bad question title, by the way. 顺便说一句,请原谅我的坏问题标题。 I couldn't think of how to put this succinctly. 我想不出如何简洁地表达这一点。

If you want the returned task to be completed successfully, rather than being cancelled, when the token is cancelled, then just call TrySetResult rather than TrySetCancelled when the token is cancelled. 如果您希望在取消令牌时成功完成而不是取消返回的任务,那么在取消令牌时只需调用TrySetResult而不是TrySetCancelled You're explicitly telling the TCS to mark the task as cancelled when you call TrySetCancelled . 您在调用TrySetCancelled时明确告诉TCS将任务标记为已取消。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM