c# - 出现错误 tasks 参数包含一个空值。参数名称:Task 并行库中的tasks with parallel.foreach
问题描述
我正在尝试执行多个内部调用一些 http 调用的任务。问题是当我使用 Parallel.ForEach 循环时出现错误:
tasks 参数包含一个空值。参数名称:任务
List<Task> TskList = new List<Task>();
Parallel.ForEach(dt.AsEnumerable(), row =>
//foreach (DataRow row in dt.Rows)
{
var oTsk =
new Task(
() =>
{
try
{
some http call
}
catch (Exception ex)
{
//AppendTextBox(row["ssub_msisdn"] as string + ", Error: " + ex.Message, txtBoxResponse);
}
});
TskList.Add(oTsk);
oTsk.Start();
}
);
var t = Task.WhenAll(TskList.ToArray());
try
{
await t;
}
catch { }
if (t.Status == TaskStatus.RanToCompletion)
{
SetLabel("Completed", lblProcessingStatus);
}
else if (t.Status == TaskStatus.Faulted)
{ SetLabel("Faulted", lblProcessingStatus); }
解决方案
您正在尝试TskList
从不同的线程访问列表而没有任何同步。这可能导致任何类型的问题。
只需这样做:
var tasks = dt.AsEnumerable().Select(row => Task.Run(() =>
{
try
{
// some http call
}
catch (Exception ex)
{
// rewrap the needed information into your custom exception object
throw YourException(ex, row["ssub_msisdn"]);
}
});
// now you are at the UI thread
foreach (var t in tasks)
{
try
{
await t;
}
catch (YourException ex)
{
AppendTextBox(ex.SsubMsisdn + ", Error: " + ex.InnerException.Message, txtBoxResponse);
}
}
Task.Run
将在线程池上启动任务,您实际上并不需要Parallel.ForEach
.
实际上,如果您的代码try
只是进行 http 调用,则根本不需要Task
!您可以通过使用异步版本来完全避免线程,例如HttpClient.GetByteArrayAsync
或HttpClient.GetStreamAsync
+ Stream.CopyToAsync
。
例如:
HttpClient client = new HttpClient(); // maybe configure it
async Task ProcessRow(Row row) // put here the correct type
{
try
{
var str = await client.GetStringAsync(row[address]);
AppendTextBox(str, txtBoxResponse);
}
catch (HttpRequestException ex)
{
AppendTextBox(row["ssub_msisdn"] + ", Error: " + ex.Message, txtBoxResponse);
}
}
var tasks = dt.AsEnumerable().Select(row => ProcessRow(row));
await Yask.WhenAll(tasks);
推荐阅读
- if-statement - SwiftUI 中的有条件文本取决于数组值
- swift - Swift/Xcode - 自定义注释视图中的按钮没有响应
- angular - 仅当检查切换时,离子表演div才
- java - 图像在处理中使用过多的 RAM
- c# - 如何修复'值不能为空。参数名称:在 SharePoint Online 中使用 CSOM 的 key 异常
- osmnx - 在 Python 中使用 osmnx 到距离内边缘的最近点
- keras - 使用 Keras 在去噪自动编码器中获取隐藏层输出
- reactjs - 在待办事项列表应用程序中创建重复项
- ios - 如何在 Xcode 11 包管理器中处理 C 文件?
- c - 将百分比添加到数字