首页 > 解决方案 > 如何处理从异步任务和程序返回的错误应该继续

问题描述

i % 2 == 0我有下面的代码,当或时在特定条件下抛出错误i % 2 != 0。我想处理错误,我想连续执行程序,怎么做?

  class Program
{
    static async Task Main(string[] args)
    {
        int i = 0;
        while (true)
        {
            i++;
            var task1 = WriteDouble(i);
            var task2 = WriteString(i);

            await Task.WhenAll(task1, task2);

            await Task.Delay(10000);
        }

    }

    private static async Task WriteString(int i)
    {
        if (i % 2 == 0)
        {
            throw new Exception("Error");
        }

        await using var file = new StreamWriter($"C:\\Temp\\test1-{i}.txt");
        await file.WriteLineAsync($"this is string-{i}");
    }

    private static async Task WriteDouble(int i)
    {
        if (i % 2 != 0)
        {
            throw new Exception("Error");
        }
        await using var file = new StreamWriter($"C:\\Temp\\test2-{i}.txt");
        await file.WriteLineAsync($"this is double-{i}");
    }
}

标签: c#task

解决方案


如果你把try-catch循环放在里面,即使抛出异常,你的循环也能继续循环:

static async Task Main(string[] args)
{
    int i = 0;
    while (true)
    {
        try 
        {
            i++;
            var task1 = WriteDouble(i);
            var task2 = WriteString(i);
            await Task.WhenAll(task1, task2);
            await Task.Delay(10000);
        }
        catch (Exception ex)
        {
        }
    }
}

更新:

Where我们可以使用linq 方法找到导致异常的任务:

var throwers = tasks.Where(task => task.Exception != null);

一个例子:

static void Main(string[] args)
{
    Task.Run(async () =>
    {
        int i = 0;
        var tasks = new List<Task>();
        while (true)
        {
            try
            {
                i++;
                var task1 = WriteDouble(i);
                var task2 = WriteString(i);
                tasks.Add(task1);
                tasks.Add(task2);
                await Task.WhenAll(tasks);
                await Task.Delay(10000);
            }
            catch (Exception ex)
            {
                var throwers = tasks.Where(task => task.Exception != null);
                var test = ex.Message;                        
            }
        }                
    }).GetAwaiter().GetResult();            
}

和其他方法:

private static async Task WriteString(int i)
{            
    throw new Exception("Error");
    await Task.Delay(1000); // 1 second delay
}

private static async Task WriteDouble(int i)
{
    await Task.Delay(1000); // 1 second delay
}

推荐阅读