并行运行2个任务,如果第一个任务完成.NET,则取消第二个任务 [英] Run 2 tasks in parallel and cancel the 2nd task if the first completes .NET

查看:84
本文介绍了并行运行2个任务,如果第一个任务完成.NET,则取消第二个任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果有两个我想在不同线程上并行运行的方法,我们将它们称为Task1和Task2.如果Task2在Task1之前完成,那么我希望将两者的结果合并到一个列表中.如果Task1完成并且Task2仍在运行,则应取消Task2,以避免进一步处理. WhenAll不起作用,因为它将等待这两个任务. WhenAny不起作用,因为如果其中任何一个先完成,它将返回.

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.

推荐答案

这是我想出的解决方案.

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

这篇关于并行运行2个任务,如果第一个任务完成.NET,则取消第二个任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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