c# - How do I keep my async method from blocking the UI? -


so i'm writing method supposed process large amount of strings , update ui every string processed. i'm using async-await pattern using progress reporter reports string main thread supposed updated. problem is: doesn't work. ui gets blocked if method running synchronously, though used await keyword. here's code looks like:

private async task processfile(string filepath, iprogress<string> progress)     {         string[] linestoprocess = file.readalllines(filepath);         int linecount = buffer.count();          await task.factory.startnew(() =>        {            (int = 0; < buffer.count(); i++)            {                //do actual processing here                progress.report(string.format("lines processed: {0} / {1}", i, linecount));            }        });     } 

and here's method calling processfile task

private async task runtask()     {         string filepath = //get filepath somehow         await processfile(filepath, new progress<string>(line =>             {                 processedlabel.text = line;             }));     } 

and finally, here's button callback runtask() task related to:

private async void button_click(object sender, eventargs e)     {         await runtask();     } 

i simplified code readability. appreciated. thank you!

i can see 2 options:

  1. you're processing many lines ui thread kept busy updating , has no time display results. fix this, don't report progress every line, every 100, 1000, or whethever number of lines appropriate you. alternative, report progress based on time, example every second. require more complicated code.
  2. you're running issue task.factory.startnew(), runs on ui thread, because that's current taskscheduler. though don't see indication in code case, don't think likely. should use task.run() instead on safe side anyway. more information, read startnew dangerous stephen cleary.

Comments

Popular posts from this blog

wordpress - (T_ENDFOREACH) php error -

Export Excel workseet into txt file using vba - (text and numbers with formulas) -

Using django-mptt to get only the categories that have items -