Run 2 tasks in parallel and cancel the 2nd task if the first completes .NET

青春壹個敷衍的年華 提交于 2019-12-13 12:42:26

问题


If have 2 methods I want to run in parallel on different threads, let's call them Task1 and Task2. If Task2 completes before Task1 then I want the results of both combined into a list. If Task1 completes and Task2 is still running, it should cancel Task2 to avoid further processing. WhenAll doesn't work because it will wait for both tasks. WhenAny doesn't work because it will return if either finish first.


回答1:


This is the solution I came up with.

static void Main(string[] args)
{
    var tokenSource = new CancellationTokenSource();
    var token = tokenSource.Token;
    var rates = new List<string>();

    try
    {
        var p44Task = Task.Factory.StartNew(() => GetP44Rates(token), token);

        var mgRates = await GetMGRates();

        rates.AddRange(mgRates);

        if (p44Task.IsCompleted && p44Task.Result.IsCompleted)
        {
            rates.AddRange(p44Task.Result.Result);
        }
        else
        {
            // Cancel the p44 task
            tokenSource.Cancel();
        }
    }
    catch (Exception e)
    {
        tokenSource.Cancel();
        Console.WriteLine(e);
    }

    foreach (var rate in rates)
    {
        Console.WriteLine(rate);
    }

    Console.ReadLine();

}

private static async Task<List<string>> GetMGRates(CancellationToken cancellationToken)
{
    var rates = new List<string>();

    for (var i = 0; i < 10; i++)
    {
        rates.Add($"MG: {i}");
        Console.WriteLine($"MG inside {i}");
        await Task.Delay(1000);
    }


    return rates;
}

private static async Task<List<string>> GetP44Rates(CancellationToken ct)
{
    var rates = new List<string>();

    for (var i = 0; i < 50; i++)
    {
        rates.Add($"P44: {i}");
        Console.WriteLine($"P44: {i}");
        await Task.Delay(1000);

        if (ct.IsCancellationRequested)
        {
            Console.WriteLine("bye from p44.");
            Console.WriteLine("\nPress Enter to quit.");

            ct.ThrowIfCancellationRequested();
        }
    }

    return rates;
}


来源:https://stackoverflow.com/questions/45380819/run-2-tasks-in-parallel-and-cancel-the-2nd-task-if-the-first-completes-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!