c# - 如何处理从异步任务和程序返回的错误应该继续
问题描述
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}");
}
}
解决方案
如果你把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
}
推荐阅读
- ios - 为什么 iOs 代码使用如此多的内存和 CPU
- arrays - 如何使用 Fortran 90 将一维数组的数据写入文件的下一列?
- react-native - NodeJS 是 React Native 应用程序背后的唯一服务器吗?
- android - 在onCreate中使用getActivity时如何让onCreate在onCreateView之前加载?
- php - Woocommerce 自定义订单状态更改日期
- google-bigquery - BigQuery上比特币交易的最大时间戳?
- javascript - 使用 JavaScript 检测文件系统上的页面何时发生更改
- javascript - 从 Controller 获取数据到 Javascript 并将其传递到 Modal Codeigniter
- function - 为什么我的 Scheme Cube-Root 程序中出现此错误?
- r - 使用 R 从网站中提取表格数据