获取错误tasks参数包含空值。参数名称:任务并行库中的任务,带有parallel.foreach

问题描述 投票:0回答:1

我正在尝试执行多个内部调用一些http调用的任务。问题是当我使用Parallel.ForEach循环时,我收到错误:

tasks参数包含null值。参数名称:任务

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); }
c# .net multithreading task-parallel-library .net-4.5
1个回答
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!您可以使用异步版本完全避免线程,例如: G。 HttpClient.GetByteArrayAsyncHttpClient.GetStreamAsync + Stream.CopyToAsync

E.克:

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);
© www.soinside.com 2019 - 2024. All rights reserved.