How to implement multi-threading and parallel execute several tasks?

后端 未结 3 502
逝去的感伤
逝去的感伤 2021-01-06 17:36

I am new to threaded programming. I have to run few tasks in PARALLEL and in Background (so that main UI execution thread remain responsive to user actions) and wait for eac

相关标签:
3条回答
  • 2021-01-06 17:57

    You can use Task library to complete:

     string[] urls = ...;
     var tasks = urls.Select(url => Task.Factory.StartNew(() => DoSomething(url)));
    

    To avoid locking UI Thread, you can use ContinueWhenAll in .NET 4.0:

    Task.Factory.ContinueWhenAll(tasks.ToArray(), _ => 
        Console.Write("All tasks Completed. Now we can do further processing");
    );
    

    If you are in the latest version of .NET, you can use Task.WhenAll instead

    0 讨论(0)
  • 2021-01-06 18:06

    If you use Net 4.0 or up, refer to the Parallel class and Task class. Joseph Albahari wrote very clear book about that: http://www.albahari.com/threading/part5.aspx#_Creating_and_Starting_Tasks

    0 讨论(0)
  • 2021-01-06 18:09

    To me it would seem like you want Parallel.ForEach

    Parallel.ForEach(myTasks, t => t.DoSomethingInBackground());
    
    Console.Write("All tasks Completed. Now we can do further processing");
    

    You can also perform multiple tasks within a single loop

    List<string> results = new List<string>(myTasks.Count);
    Parallel.ForEach(myTasks, t =>
    {
        string result = t.DoSomethingInBackground();
        lock (results)
        { // lock the list to avoid race conditions
            results.Add(result);
        }
    });
    

    In order for the main UI thread to remain responsive, you will want to use a BackgroundWorker and subscribe to its DoWork and RunWorkerCompleted events and then call

    worker.RunWorkerAsync();
    worker.RunWorkerAsync(argument); // argument is an object
    
    0 讨论(0)
提交回复
热议问题