0

Is there a way to use TaskContinuationOptions like a finally?

Here is my code

        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);

Here is my question

I wanted to use last ContinueWith like a finally. So, I changed my last ContinueWith phrase like this

        }).ContinueWith(x =>
        {
            HideLoading();
        }, TaskContinuationOptions.OnlyOnRanToCompletion | 
           TaskContinuationOptions.OnlyOnFaulted);

I thought it be used when the last task is complete or fault.

But It throws a error.

I hope there is a good way to solve my problem.

thank you for reading my question.

4

1 回答 1

2

如果您不指定 aTaskContinuationOptions那么它将在所有状态下运行 - 无论Task是故障(异常)、取消还是成功完成。

例如:

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.
于 2018-03-13T03:15:51.287 回答