C# AutoResetEvent WaitOne stopped by dispatcher -


private void waitfordrivetobecomeready() {     autoresetevent syncevent = new autoresetevent(false); //set wait signal use later      //dispatcher able change stuff in xaml within thread     action action1 = new action(delegate() { grdmain.children.add(notification); });     action action2 = new action(delegate() { grdmain.children.remove(notification); });     thread restorethread1 = new thread(()=>{         grdmain.dispatcher.invoke(system.windows.threading.dispatcherpriority.background, action1); //show notification          thread.sleep(1500); //sleep bit...          grdmain.dispatcher.invoke(system.windows.threading.dispatcherpriority.background, action2); //hide notification          syncevent.set(); //signal continue @ *.waitone()     });     restorethread1.start();      syncevent.waitone(); //let main thread wait until *.set(); called } 

the above code works perfect if comment out 2 grdmain.dispatcher.invoke(...);. works perfekt if comment out *.set(); , *.waitone(); whyyyy? need both ^^. don't it...

assuming waitfordrivetobecomeready called on dispatcher's thread, explicitly introducing deadlock.

consider course of execution

  • you set reset event
  • the thread starts executing
  • the dispatcher thread calls syncevent.waitone(), thread blocked until event gets set
  • the second thread executes dispatcher.invoke; puts message in dispatcher's queue , waits until processes (on main thread)

so have main thread blocked waiting event set second thread. , have second thread blocked waiting main thread process message. textbook deadlock.

in general, waiting on ui thread bad; it's easy deadlocks this, if works, you're still blocking ui updating, creating unresponsive program. based on snippet above it's difficult how best reorganize code don't have block ui thread, seems concept (preparing drive, , doing once it's ready) candidate asynchronous method.


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -