c# - How Task.WaitAll() Behave? -


i have created list of task, this:

public void a() {  }  public void b() {  }  public void c() {  }  public void ex() {    task.waitall(task.factory.startnew(a), task.factory.startnew(b), task.factory.startnew(c));    var p=true; } 

now question that. tasks inside list execute 1 one or execute in parallel.

p=true

"p" set when tasks done or before done?

for first question:

will tasks execute 1 one or asynchronously.

(here, imagine meant concurrently, not same)

using startnew run task in current taskscheduler. default means use threadpool and, if there available slots in thread pool, run in parallel. if slots taken in task pool, may throttle execution of tasks in order avoid cpu overwhelmed, , tasks may not executed @ same concurrently: there no guarantees.

this simplified explanation , more complete , detailed explanation on scheduling strategy explained on taskscheduler documentation.

as side note. documentation starttask mentions subtle difference between startnew(action) , run(action). not equivalent, unlike stated in other answers.

starting .net framework 4.5, can use task.run(action) method quick way call startnew(action) default parameters. note, however, there difference in behavior between 2 methods regarding : task.run(action) default not allow child tasks started taskcreationoptions.attachedtoparent option attach current task instance, whereas startnew(action) does.

for second question

"p" set when tasks done or before done?

the short answer yes.

however, should consider using approach 1 block thread , waiting idly. alternative give control caller if can , thread freed , can used cpu. true if thread on code running part of threadpool.

therefore, should prefer using whenall(). returns task, can awaited or on continuewith can called

example:

var tasks = new task[] {task.factory.startnew(a), task.factory.startnew(b), task.factory.startnew(c)};  await task.whenall(tasks); 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -