得到错误任务参数包含一个空值。参数名称:Task并行库中带有parallel.foreach的任务

时间:2019-02-13 10:19:52

标签: c# .net multithreading task-parallel-library .net-4.5

我正在尝试执行多个内部调用一些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); }

1 个答案:

答案 0 :(得分:1)

您正在尝试从其他线程访问列表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!您可以通过使用异步版本(例如e)完全避免线程。 G。 HttpClient.GetByteArrayAsyncHttpClient.GetStreamAsync + Stream.CopyToAsync

E。 g。:

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