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

后端 未结 3 501
逝去的感伤
逝去的感伤 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 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 results = new List(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
    

提交回复
热议问题