c# - List of tasks starts them synchronously - I would like them to start all at once -


private async task maintask(cancellationtoken token) {     list<task> tasks = new list<task>();         {         var data = staticvariables.alldata;          foreach (var datapiece in data)         {             tasks.add((new task(() => dosomething(data))));         }          parallel.foreach(tasks, task => task.start());         await task.whenall(tasks);         tasks.clear();         await task.delay(2000);     } while (!token.iscancellationrequested); } 

the above function supposed start number of dosomething(task) methods , run them @ same time. dosomething has timeout of 2 sec before returns false. after testing, seems part between

await task.whenall(tasks);

and

tasks.clear()

is taking 2 sec * number of tasks. seem that:

  • start task
  • do or abort after 2 sec
  • start next task
  • ...

how start @ same time , perform operations simultaneously?

edit

doing so:

await task.whenall(data.select(datapiece => task.run(() => dosomething(datapiece)))

results in horrible performance (around 25 sec complete old code, 115 sec complete this)

first of all, should utilize task.run instead of creating , starting tasks in separate steps.

you can inside loop or linq style. if use linq, ensure not stuck deferred execution, second task starts after first 1 completed. create list, array or other persistent collection of selected tasks:

await task.whenall(data.select(datapiece => task.run(() => dosomething(datapiece)).tolist()); 

the other problem content of dosomething. long synchronous method, block executing thread until done. inherently asynchronous operation (like pinging network address), redesigning method can prevent thread blocking behavior.

another option, answered matthew watson increase amount of available threads, each task can run in own thread. not best option, if have many tasks have long blocking time without doing actual work, more threads work done.

more threads not if tasks using available physical resources, cpu or io bound work.


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -