C# 有没有一种方法可以像finally一样使用TaskContinuationOptions
有没有一种方法可以像finally一样使用TaskContinuationOptions 这是我的密码C# 有没有一种方法可以像finally一样使用TaskContinuationOptions,c#,multithreading,task,continuewith,C#,Multithreading,Task,Continuewith,有没有一种方法可以像finally一样使用TaskContinuationOptions 这是我的密码 ShowLoading(); Task.Factory.StartNew((Action)(() => { _broker.SetDrugDataFromAPI(newDrug); })).ContinueWith(x => { lock (this)
ShowLoading();
Task.Factory.StartNew((Action)(() =>
{
_broker.SetDrugDataFromAPI(newDrug);
})).ContinueWith(x =>
{
lock (this)
{
//Do Something to UI
}
}, _uiScheduler).ContinueWith(x =>
{
//Do Somehting after change UI
}).ContinueWith(x =>
{
HideLoading();
}, TaskContinuationOptions.OnlyOnFaulted);
这是我的问题
我想用last ContinueWith作为finally。
所以,我把最后一个连续体改成这样
}).ContinueWith(x =>
{
HideLoading();
}, TaskContinuationOptions.OnlyOnRanToCompletion |
TaskContinuationOptions.OnlyOnFaulted);
我认为它可以在最后一项任务完成或出现故障时使用
但它抛出了一个错误
我希望有一个好办法来解决我的问题
感谢您阅读我的问题。如果您没有指定
任务继续选项
,则它将在所有状态下运行-无论任务
是否出现故障(异常)、取消或成功完成
例如:
using System;
using System.Threading;
using System.Threading.Tasks;
public class Program
{
public static async Task Main()
{
using (var cts = new CancellationTokenSource())
{
var task = Task.CompletedTask
.ContinueWith(t => Console.WriteLine("Run after completed"))
.ContinueWith(t => throw new Exception("Blow up"))
.ContinueWith(t => Console.WriteLine("Run after exception"))
.ContinueWith(t => cts.Cancel())
.ContinueWith(t => Console.WriteLine("This will never be hit because we have been cancelled"), cts.Token)
.ContinueWith(t => Console.WriteLine("Run after cancelled."));
await task;
}
}
}
此程序产生以下输出:
Run after completed
Run after exception
Run after cancelled.
如果未指定
TaskContinuationOptions
,则它将在所有状态下运行-无论任务是否出现故障(异常)、已取消或已成功完成
例如:
using System;
using System.Threading;
using System.Threading.Tasks;
public class Program
{
public static async Task Main()
{
using (var cts = new CancellationTokenSource())
{
var task = Task.CompletedTask
.ContinueWith(t => Console.WriteLine("Run after completed"))
.ContinueWith(t => throw new Exception("Blow up"))
.ContinueWith(t => Console.WriteLine("Run after exception"))
.ContinueWith(t => cts.Cancel())
.ContinueWith(t => Console.WriteLine("This will never be hit because we have been cancelled"), cts.Token)
.ContinueWith(t => Console.WriteLine("Run after cancelled."));
await task;
}
}
}
此程序产生以下输出:
Run after completed
Run after exception
Run after cancelled.
抛出了哪个错误?为什么不在任务中使用finally块呢?谢谢您的评论。在ContinueWith短语中有一个for短语。当我在任务中使用阶段时,我无法同步任务。当任务进入任务中的for阶段时,它进入任务外。所以,我不能使用try finally phaseWich错误抛出?为什么不在任务中使用finally块呢?谢谢您的评论。在ContinueWith短语中有一个for短语。当我在任务中使用阶段时,我无法同步任务。当任务进入任务中的for阶段时,它进入任务外。所以,我不能使用try finally阶段