受欢迎的博客标签

多核CPU并行编程:.How to:Write a simple Parallel.For loop (stock)

Published

 

Convert this for code to Parallel.For step by step

step 1: loop for

 // number of threads for parallel computations
            int threadsCount = System.Environment.ProcessorCount;

            DzhDataProvider dzhDataProvider = new DzhDataProvider();
            List<KData> ListKDataDay_SH000001 = dzhDataProvider.GetKDataDay("SZ399001");
            dzhDataProvider.Close();

            for (int index = 0; index < ListKDataDay_SH000001.Count; index++)
            {
                // DoSomething();
            }

step 2:

  Parallel.For(0, ListKDataDay_SH000001.Count, index =>
            {
                Console.WriteLine($"{actionName}->CheckReportFileExistParallel线程Id, thread = {Thread.CurrentThread.ManagedThreadId}");
                // DoSomething();
                Thread.Sleep(10);
            });

 

Step 3:

 Parallel.For(1, 100, (i, ParallelLoopState) =>
            {  
                // 当某一个循环单元的数大于30,
                // 则跳出当前执行单元,等待其他执行单元结束
                // 所有执行单元结束后退出Parallel.For的执行
                if (i > 30)
                {
                    // 跳出当前执行单元
                    ParallelLoopState.Break();
                    return;//不加return,可能会发生该进程资源未释放。
                }
            });

How can I convert this foreach code to Parallel.ForEach?

Here's a simple example :

string[] lines = File.ReadAllLines(txtProxyListPath.Text);
List<string> list_lines = new List<string>(lines);

foreach (string line in list_lines)
{
    //My Stuff
}

Sample2:

// Sequential version
foreach (var item in sourceCollection)
{
    Process(item);
}

// Parallel equivalent
Parallel.ForEach(sourceCollection, item => Process(item));

How can I rewrite this example with Parallel.ForEach?

step 1:Write a simple Parallel.ForEach loop

detail:https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/how-to-write-a-simple-parallel-foreach-loop

Parallel.ForEach(files, (currentFile) =>
                                {
                                
                                    string filename = Path.GetFileName(currentFile);
                                   
                                });

 

Step 2: Add ParallelLoopState

   Parallel.ForEach(elements, (element, ParallelLoopState) =>
2             {
3                 if (element == "")
4                 {
5                     ParallelLoopState.Break();
6                     return;
7                 }
8             });

 

  Parallel.ForEach(listcodetable, (item, ParallelLoopState) =>
            {


                this._logger.LogInformation($"{DateTime.Now} {actionName}  :GetMultiFilterPankouSearchByParallelForEachLoop,Thread Id={Thread.CurrentThread.ManagedThreadId}");

                //old 
                //if (!(Stockso.Core.CommonHelper.GetStockType(item) == StockType.ISGP)) //股票
                //    continue;

                //replace with this code
                if (!(Stockso.Core.CommonHelper.GetStockType(item) == StockType.ISGP)) //股票
                {
                    ParallelLoopState.Break();
                    return;
                }



                //2.每只股票按天循环
                for (int i = 0; i < listDayk.Count; i++)
                {

                    if (!PRPDataProvider[i].StockExist(item)) continue;



                    if (item == "SZ300365") { int jj = 0; }

                    //获取股票某天的全部分笔成交数据
                    List<Report> listreport = PRPDataProvider[i].GetReport(item);

                    List<KData> listminuteK = Stockso.Core.CommonHelper.ConvertReportToKMinute(listreport);

                    //Stockso.Core.CommonHelper CommonHelper=new Stockso.Core.CommonHelper();

                    //Stockso.Core.DataCycleConverter DataCycleConverter = new Stockso.Core.DataCycleConverter();

                    //List<KData> m_kdMin301 = DataCycleConverter.ConvertKData(listminuteK, 30);

                    //Stockso.Core.DataCycleConverter DataCycleConverter1 = new Stockso.Core.DataCycleConverter();
                    //List<KData> m_kdDay1 = DataCycleConverter1.ConvertKData(listminuteK, 1440);

                    //List<KData> m_kdMin302 = DataCycleConverter.ConvertKData(listminuteK, 30);

                    //分钟线转30分钟线
                    List<KData> m_kdMin30 = Stockso.Core.CommonHelper.ConvertKData(listminuteK, 60);

                    List<KData> m_kdDay = Stockso.Core.CommonHelper.ConvertKData(listminuteK, 1440);






                    if (m_kdDay.Count == 0) continue;

                    string sinfo = "";
                    string scode = "";

                    switch (reportMinuteMenuId)
                    {

                        case (int)PanKouDataMenu.ktypeFallSharplyEarlyTrading:
                            #region 早盘急跌后横盘的股票 条件:开盘价是当天最高价,第一个小时内最低价,
                            if ((m_kdMin30[0].m_fLow == m_kdDay[0].m_fLow) && (m_kdDay[0].m_fClose < m_kdDay[0].m_fOpen)) //阴线
                                if ((m_kdMin30[0].m_fHigh == m_kdDay[0].m_fHigh) && (m_kdDay[0].m_fClose < m_kdDay[0].m_fOpen))
                                {

                                    sinfo = sinfo + m_kdMin30[0].StockCode + " 最低价时间:" + m_kdDay[0].m_fLowStartTime.ToString() + " 最低价:" + m_kdDay[0].m_fLow.ToString() + reportMinuteMenuId.ToString() + "\n";

                                    this._logger.LogInformation($"{actionName}  早盘急跌后横盘的股票:{sinfo} 总笔数: {scode}\n");

                                    if (!scode.Contains(m_kdMin30[0].StockCode.Replace("SZ", "0").Replace("SH", "1")))
                                    {
                                        scode = scode + m_kdMin30[0].StockCode.Replace("SZ", "0").Replace("SH", "1") + "\n";
                                    }


                                    //存结果信息
                                    {

                                        SearchResultStockModel searchResultStockModel = new SearchResultStockModel();
                                        searchResultStockModel.StockCode = m_kdMin30[0].StockCode;
                                        searchResultStockModel.StartTime = m_kdDay[0].m_fLowStartTime;
                                        searchResultStockModel.Message = $"最低价格:{m_kdDay[0].m_fLow.ToString()} 最低价格时间:{m_kdDay[0].m_fLowStartTime.ToString()}";

                                        //存入列表
                                        searchResultStockModelList.Add(searchResultStockModel);
                                    }
                                }


                            break;
                            #endregion
                    }

                    //     

                }//end for (int i = 0; i < listDayk.Count; i++)

            });