WPF Async Task locking UI -


i know i'm missing stupid, "startprocess" method making ui unresponsive , no amount of googling , tutorials has led me answer.

here code:

    public mainwindow()     {         initializecomponent();         txtblock.text = "testing";         initialize();     }      public void initialize()     {         uischeduler = taskscheduler.fromcurrentsynchronizationcontext();          startprocess();     }      async void startprocess()     {          task<int> result = task.factory.startnew(() =>         {             txtblock.text += ("\n starting updater");             while (true)             {                 thread.sleep(3000);             }             return 0;         }, cancellationtoken.none, taskcreationoptions.longrunning, uischeduler);     } 

some background: i'm building app has poll db every 5mins , update ui to-do list user, hence while(true) loop. app has poll db continuously throughout lifetime.

well, asked tpl invoke func in ui thread, obeys words.

in startnew pass uischeduler taskscheduler, task queued dispatcher invoked ui thread.

if don't want execute in ui thread use taskscheduler.default, doing can't update txtblock.text inside func. need marshal call ui thread or set txtblock.text outside func before startnew.

always prefer task.run if you're in .net 4.5, aware startnew dangerous.

couple of things note:

  • note you're not leveraging async feature @ all. without await keyword method not @ async. don't need async keyword @ all(infact you'll compiler warning, please pay attention compiler says).
  • avoid async void methods(except in event handlers), use async task if don't need return value, await in caller or attach continuation , forth.

update add code:

async task startprocess() {     while (true)     {         var result = await task.run(()=> methodwhichcallsdbandreturnssomething());         txtblock.text = result.tostring();//use result , update ui         await task.delay(5 * 60 * 1000);//await 5 mins     } } 

Comments

Popular posts from this blog

javascript - how to protect a flash video from refresh? -

visual studio 2010 - Connect to informix database windows form application -

android - Associate same looper with different threads -