开发者

eventhandler on button in wpf process while any other click on form is queued

. I am quite new to WPF and have a question regarding the queuing of event handler. In the application that I am developing using WPF have the following code on the click of a button

private void ButtonUpdate_Click(object sender, RoutedEventArgs e)
 {
  try 
  {
     Cursor = Cursors.Wait;                 
     Processor.UpdateData(); 
  }
  catch (RemoteConnection x)
  {
    ShowConnectionError(this, x);
  }
  finally
  {
            Cursor = Cursors.Arrow;
   }

When I click on the this button, the method Processor.UpdateData(), starts processing and cursor is set to hour glass. Now in the meantime if user presses any other button on the screen or type in the textbox,开发者_运维知识库 that is done immediately after the processing of the above event handler. It seems these events are queued in dispatcher queue. Can you please help me to avoid this situation?


Well to avoid such scenario i.e. user should not be able to click or generate another event while one is already going on what you can do is something like this

  private void ButtonUpdate_Click(object sender, RoutedEventArgs e)
    {
       //disable button here so no more clicking until processing is done
       //start a backgroundworker that will do the processing
    }

   BackgroundWorker()
   {
       try 
       {
          Cursor = Cursors.Wait;                 
          Processor.UpdateData(); 
       }
       catch (RemoteConnection x)
       {
          ShowConnectionError(this, x);
       }
       finally
       {
          Cursor = Cursors.Arrow;
          //enable button again using Dispatcher
       }
   }


What exactly are you trying to avoid? Fundamentally, it's a bad idea to block the UI thread for any significant length of time. It would be better to disable any controls you don't want to raise events, then launch the work on a different thread. When it's finish, marshal back to the UI thread using Dispatcher, update the UI, and then re-enable the controls you disabled before.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜