Speed up loop using multithreading in C# (Question)

后端 未结 6 735
南笙
南笙 2020-12-13 15:40

Imagine I have an function which goes through one million/billion strings and checks smth in them.

f.ex:

foreach (String item in ListOfStrings)
{
            


        
6条回答
  •  南方客
    南方客 (楼主)
    2020-12-13 16:38

    You need to split up the work you want to do in parallel. Here is an example of how you can split the work in two:

    List work = (some list with lots of strings)
    
    // Split the work in two
    List odd = new List();
    List even = new List();
    for (int i = 0; i < work.Count; i++)
    {
        if (i % 2 == 0)
        {
            even.Add(work[i]);
        }
        else
        {
            odd.Add(work[i]);
        }
    }
    
    // Set up to worker delegates
    List oddResult = new List();
    Action oddWork = delegate { foreach (string item in odd) oddResult.Add(CalculateSmth(item)); };
    
    List evenResult = new List();
    Action evenWork = delegate { foreach (string item in even) evenResult.Add(CalculateSmth(item)); };
    
    // Run two delegates asynchronously
    IAsyncResult evenHandle = evenWork.BeginInvoke(null, null);
    IAsyncResult oddHandle = oddWork.BeginInvoke(null, null);
    
    // Wait for both to finish
    evenWork.EndInvoke(evenHandle);
    oddWork.EndInvoke(oddHandle);
    
    // Merge the results from the two jobs
    List allResults = new List();
    allResults.AddRange(oddResult);
    allResults.AddRange(evenResult);
    
    return allResults;
    

提交回复
热议问题