标签: parallel.foreach

使用Parallel.ForEach时出错

最初,我正在使用foreach来完成我的任务.但是,我想提高任务的效率.所以,我想使用Parallel.ForEach来完成我的任务.

但是,错误"未将对象引用设置为实例".发生了.

这是我的代码:

System.Threading.Tasks.Parallel.ForEach(items, item =>
        {
             System.Threading.Tasks.Parallel.ForEach(item.a, amount =>
                    {
                         WriteToCsv(file, amount.columna, count);
                          count++;
                     });

         });
Run Code Online (Sandbox Code Playgroud)

如果我使用foreach(项目中的var项目)和foreach(项目中的数量),代码工作正常.

我错过了Parallel.ForEach方法吗?

c# linq parallel.foreach

0
推荐指数
1
解决办法
2273
查看次数

Parallel.Foreach vs Foreach用于数据迁移过程

我有一份车辆清单......对于每辆车,我正在做一些移民工作.

foreach (vehicles)
{

1 : Do database table migration for that vehicle
2 : Call an API and save them to database

}
Run Code Online (Sandbox Code Playgroud)

为了提高性能,我将其平行如下:

Parallel.Foreach(vehicles)
{
--same
}
Run Code Online (Sandbox Code Playgroud)
  1. 这是正确的方法吗?因为我的理解是,它将为每个请求的车辆创建新的线程,事情应该快速.

  2. 并行TASK会改进吗?

  3. 保持最大并行数是否好?如果是,如何确定该因素?

c# asp.net parallel-processing performance parallel.foreach

0
推荐指数
1
解决办法
299
查看次数

取消Parallel.ForEach或使用async等待

我有这个事件:

private void  TextBoxSearchText_TextChanged(object sender, TextChangedEventArgs e)
{
    searchText();
}
Run Code Online (Sandbox Code Playgroud)

我希望取消这个并行方法,并在文本框文本更改时启动一个新方法,并希望我的文本框能够响应我的新文本输入,这将锁定,直到结果出现在列表框中.

List<TextList> oSelected;
private void searchText()
{
string strSearchText = TextBoxSearchText.Text;
    oSelected = new List<TextList>();            
    Parallel.ForEach(oTextList, item  =>
    {
        Match myMatch = Regex.Match(item.EnglishText.ToString(), "\\b" + strSearchText.ToString().ToLower() + @"\w*", RegexOptions.IgnoreCase);
        if (!myMatch.Success)
        {
            return;
        }

        oSelected.Add(new TextList
        {
            Id = item.Id,
            EnglishText = item.EnglishText
        });
    });

    ListBoxAllTexts.ItemsSource = oSelected;
}
Run Code Online (Sandbox Code Playgroud)

是否可以使用async和awiat来完成这项工作?哪一个更适合在近100万行文本中搜索文本?我读了很多关于异步和等待但我无法理解如何在我的工作中使用它.谢谢

c# asynchronous async-await parallel.foreach

0
推荐指数
1
解决办法
406
查看次数

多线程问题,也许是使用Foreach的DeadLock

Parallel.ForEach继续运行,我的程序没有结束.我无法追踪第一次迭代后的位置.我的猜测是获得死锁并继续进行上下文切换.

private void ReadInputFile()
{
    var collection = new ConcurrentBag<PropertyRecord>();
    var lines = System.IO.File.ReadLines(InputFileName);
    int i = 0;
    int RecordsCount = lines.Count();
    Parallel.ForEach(lines, line =>
    {
        if (string.IsNullOrWhiteSpace(line))
        {
            return;                    
        }

        var tokens = line.Split(',');
        var postalCode = tokens[0];
        var country = tokens.Length > 1 ? tokens[1] : "england";

        SetLabelNotifyTwoText(
            string.Format(
                "Reading PostCode {0} out of {1}"
                i,
                lines.Length));

        var tempRecord = GetAllAddesses(postalCode, country);
        if (tempRecord != null)
        {
            foreach (PropertyRecord r in tempRecord)
            {
                collection.Add(r);
            }
        }    
    }); …
Run Code Online (Sandbox Code Playgroud)

.net c# task-parallel-library parallel.foreach

0
推荐指数
1
解决办法
306
查看次数

如何使用并行foreach添加字符串而没有任何问题?

这是我目前的代码:

Parallel.ForEach(Arguments, Argument =>
{
    if (Argument != Command_Name)
    {
        WebRequest web_request = WebRequest.Create("https://www.aol.com/?command=1&domain=" + Argument);
        web_request.Timeout = 5000;
        ((HttpWebRequest)web_request).UserAgent = "Mozilla Firefox 5.0";
        HttpWebResponse web_response = (HttpWebResponse)web_request.GetResponse();
        StreamReader response = new StreamReader(web_response.GetResponseStream(), Encoding.UTF8);
        Message += Argument + " => " + response.ReadToEnd() + Environment.NewLine;
    }
});
Run Code Online (Sandbox Code Playgroud)

此代码无法正常工作,我正在寻找一个小的替代品.此代码返回Message字符串中的一些参数...多线程字符串添加的好方法是什么?这就是我需要的.

更多信息:消息字符串有时会返回a,b和c,而其他消息字符串只返回a或b ...

感谢您的帮助,谢谢!

c# string parallel-processing parallel.foreach

0
推荐指数
1
解决办法
2127
查看次数

使用Parallel.ForEach执行多个帖子

这是我的语法,但我的编译错误仍然存​​在 Parallel.ForEach()

System.Data.DataRow是一个类型,但像变量一样使用

我确信这是一件简单的事,我只是在俯视.下面是我的完整语法,如果有人可以帮助我找到我错过的内容,我将非常感激!

private void TryParallel()
{
  Dictionary<string, string> dic = new Dictionary<string, string>();
  string strEndpointURL = string.Format("http://sitetosenddatato.com/post");
  SqlDataReader reader;
  string strPostData = "";
  string strMessage = "";
  DataSet grds = new DataSet();
  grds = GetSQLResults();
  if (grds.Tables[0].Rows.Count >= 1)
  {
    Parallel.ForEach(DataRow, grds.Tables[0].Rows =>
    {
        dic.Add("userID", reader.GetValue(0).ToString());
        dic.Add("name", reader.GetValue(1).ToString());
        dic.Add("address", reader.GetValue(2).ToString());
        dic.Add("city", reader.GetValue(3).ToString());
        dic.Add("state", reader.GetValue(4).ToString());
        dic.Add("zip", reader.GetValue(5).ToString());
        dic.Add("Phone", reader.GetValue(6).ToString());
    });
  }
  System.Web.Script.Serialization.JavaScriptSerializer json = new System.Web.Script.Serialization.JavaScriptSerializer();
  foreach (var d in dic) { strPostData += d.Key + "=" + Server.UrlEncode(d.Value) …
Run Code Online (Sandbox Code Playgroud)

c# asp.net parallel.foreach

0
推荐指数
1
解决办法
254
查看次数

为什么异步Parallel.ForEach中的异常会使应用程序崩溃?

如果在控制台应用程序中运行而不是将其抛出AggregateException并被外部捕获,以下的崩溃为什么会崩溃try/catch

I've simplified the use case for the await for brevity, but in the relevant code I am indeed trying to execute an awaitable Task of importance.

var list = new List<string>() {"Error"};

        try
        {
            Parallel.ForEach(list, new ParallelOptions()
            {
                MaxDegreeOfParallelism = 8
            }, async listEntry =>
            {
                await Task.Delay(5000);
                throw new Exception("Exception");
            });
        }
        catch (Exception ex)
        {
            //never hits, the application crashes
        }

        Console.ReadLine();
Run Code Online (Sandbox Code Playgroud)

I note that the following does not cause the application to …

c# exception task-parallel-library parallel.foreach

0
推荐指数
1
解决办法
1051
查看次数

C# - 如何为每个方法列表并行?

我有方法列表,需要并行化它们.如何在C#中做到这一点?我看到有一个Parallel命名空间?如何使用它?

method1()
method2()
method3()
method4()
Run Code Online (Sandbox Code Playgroud)

c# parallel-processing multithreading task parallel.foreach

0
推荐指数
1
解决办法
150
查看次数

Parallel.ForEach()没有得到预期的结果

在我的web api控制器中,我使用Parallel.ForEach()循环遍历列表.我有一个计数器,我在Parallel.ForEach代码中递增.我注意到每次运行它时计数器都是一个变量号,它永远不会像我用Parallel.ForEach()循环的列表一样高.似乎Parallel.ForEach()在完成循环遍历所有元素之前不等待回来.

// get all the new records from the csv
var newData = csv.GetRecords<MyEFTable>().ToArray();
int count = 0;
Parallel.ForEach(newData, (d) => {
  count++});
Run Code Online (Sandbox Code Playgroud)

newData有6588项,计数一般在3400左右,但每次都是可变的.这很奇怪.

c# parallel.foreach

0
推荐指数
1
解决办法
351
查看次数

当并行foreach中的公共变量增加时,如何获取下一个值?

我有一个在foreach中更新的公共变量,它是一个计数器,所以我想让一个并行foreach中的下一个计数器.

我有类似的东西:

int myCommonCounter = 5;
Parallel.Foreach(myList, (iterator, state) =>
{
    if(iterator.MyProperty == X)
    {
        iterator.Position = miCommonCounter;
        miCommonCounter = miCommonCunter + 1;
    }
});
Run Code Online (Sandbox Code Playgroud)

我想避免属性iterator.Position中的间隙,也避免重复.

我已经看到了一个例子来处理部分结果的总和,例如在本文档中,但它并不是我需要的相同情况.

因此,我想知道是否有任何更新计数器以避免在并行foreach内部更新时出现间隙和重复.

谢谢.

c# task-parallel-library parallel.foreach

0
推荐指数
1
解决办法
87
查看次数