locked
Thread.Sleep inside Dispatcher.BeginInvoke ? RRS feed

  • Question

  • Hi, I'm having problem understanding why following code lock's up Silverlight application. Hope you can help me.
    I will use BackgroundWorker class to execute some method from DLL file.
    If Thread.Sleep is NOT used inside Dispatcher.BeginInvoke then no locking occur, but this is no good for me because Thread.Sleep can be inside method which I call.


    BackgroundWorker worker = new BackgroundWorker();
    worker.DoWork += new DoWorkEventHandler(worker_DoWork);
    worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
    worker.RunWorkerAsync();
    Cursor = Cursors.Wait;
    
    
    
    void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
         Cursor = Cursors.Arrow;
         MessageBox.Show("Done ... :-)");
    }
    
    void worker_DoWork(object sender, DoWorkEventArgs e)
    {
    
         Dispatcher.BeginInvoke(() =>
         {
              CallUserMethod("DllSample.dll", "SimpleClass", "CalculateTwoNumbers", new object[] { 10, 20 });
         });
    
    }
    
    void CallUserMethod(string dllPath, string className, string methodName, object[] @params)
    {
         // will use System.Reflection to call some method in DLL file,
         // but for this example just pause 5 seconds to simulate long running function.
         System.Threading.Thread.Sleep(5000);
         int number = 1 + 2;
    }
    
    Is there some alternative perhaps ? Thanks in advance, Zoran
    Tuesday, August 25, 2009 3:35 AM

Answers

  • Dispatcher.BeginInvoke queues your work to run on the UI Thread when it can.

    You are running a thread.sleep on the actual UI Thread which will cause it to become non-responsive / locked.

    I would only use Thread.Sleep on a background thread for this reason unless of course there is some business case for locking the front end.

    Tuesday, August 25, 2009 3:54 AM