是否可以确保ContinueWith执行? [英] Is ContinueWith guaranteed to execute?

查看:62
本文介绍了是否可以确保ContinueWith执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码充当了轻量,无阻塞的关键部分.我希望无论 Task.Run 子句中的 _func cancellationToken 发生什么情况,都可以保证继续运行在其 finally 块中的 Exit 语句将始终执行.

I've got a bit of code that is acting as a light weight, non-blocking, critical section. I am hoping that no matter what happens with _func and cancellationToken in the Task.Run clause, that the continuation is guaranteed to run such that the Exit statement in its finally block will always execute.

可以安全地假设下面的finally块(在此过程中没有灾难性的失败)将以与

Is it safe to assume that the finally block below, short of catastrophic failure in the process, will be executed with roughly the same guarantees that finally normal operates with?

if (Enter())
{
    Task.Run<T>(_func, cancellationToken)
        .ContinueWith((antecedent) =>
        {
            try
            {
                antecedent.Wait(cancellationToken);
                Interlocked.Exchange<T>(ref _result, antecedent.Result);
            }
            catch (AggregateException e)
            {
                Interlocked.Exchange(ref _exceptions, e);
            }
            catch (OperationCanceledException)
            {
                ResetState();
            }
            catch (Exception e)
            {
                Interlocked.Exchange(ref _exceptions, new AggregateException(e));
            }
            finally
            {
                Exit();
            }
        })
}

推荐答案

基于

返回的任务要等到当前任务完成后才能安排执行,无论该任务是由于成功运行而完成,还是由于未处理的异常而导致错误,还是由于被取消而提前退出.

The returned Task will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled.

因此,除非 _func 永不返回(例如在无限循环中运行),否则延续将始终运行.

So, unless _func never returns (runs in an infinite loop for example), then the continuation will always run.

并且在继续运行时,可以确保按C#的规则执行finally块.

And when the continuation runs, the finally block is guaranteed to execute as per the rules of C#.

所以答案是肯定的(当然,除非 _func 永远不会返回).

So the answer is yes (unless of course _func never returns).

这篇关于是否可以确保ContinueWith执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆