c# - Parallel.ForEach using Thread.Sleep equivalent -


so here's situation. need make call web site starts search. search continues unknown amount of time, , way know if search has finished periodically querying website see if there's "download data" link somewhere on (it uses strange ajax call on javascript timer check backend , update page, think).

so here's trick. have hundreds of items need search for, 1 @ time. have code looks little bit this:

var items = getitems(); parallel.foreach(items, item => {    startsearch(item);    var finished = issearchfinished(item);    while(finished == false)    {       finished = issearchfinished(item); //<--- how delay action 30 secs?    }    downloaddata(item); } 

now isn't real code, because there things cause issearchfinished false.

obvious infinite loop danger aside, how correctly keep issearchfinished() calling on , on , over, instead call every, say, 30 seconds or 1 minute?

i know thread.sleep() isn't right solution, , think solution might accomplished using threading.timer() i'm not familiar it, , there many threading options i'm not sure use.

it's quite easy implement tasks , async/await, noted @kevins in comments:

async task<itemdata> processitemasync(item item) {     while (true)     {         if (await issearchfinishedasync(item))             break;         await task.delay(30 * 1000);     }     return await downloaddataasync(item); }  // ...  var items = getitems(); var tasks = items.select(i => processitemasync(i)).toarray(); await task.whenall(tasks); var data = tasks.select(t = > t.result); 

this way, don't block threadpool threads in vain bunch of i/o-bound network operations. if you're not familiar async/await, async-await tag wiki might place start.

i assume can convert synchronous methods issearchfinished , downloaddata asynchronous versions using httpclient non-blocking http request , returning task<>. if unable so, still can wrap them task.run, await task.run(() => issearchfinished(item)) , await task.run(() => downloaddata(item)). not recommended, have hundreds of items, sill give better level of concurrency parallel.foreach in case, because won't blocking pool threads 30s, asynchronous task.delay.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

jsf - How to ajax update an item in the footer of a PrimeFaces dataTable? -

django - CSRF verification failed. Request aborted. CSRF cookie not set -