0

Possible Duplicate:
Cross-thread operation not valid

I m trying to run this 2 thread to control the undo and redo button to be enabled or not, but i m getting cross thread not valid, i tried to create an invoke but i couldn't using the button

here is my code

    private Thread _undoThread;
    private Thread _redoThread;

    _undoThread = new Thread(UndoEnabledCheck);
    _undoThread.Start();
    _redoThread = new Thread(RedoEnabledCheck);
    _redoThread.Start();

    private void UndoEnabledCheck()
    {
       UndoButton.Enabled = _undoBuffer.CanUndo;
    }

    private void RedoEnabledCheck()
    {
       RedoButton.Enabled = _undoBuffer.CanRedo;
    }
Community
  • 1
  • 1
jprbest
  • 717
  • 6
  • 15
  • 32

3 Answers3

3

The reason for this is that you cannot do anything to the Form unless you are on the Form's Thread. This will then use the standard Form dispatch thread. In order to update the form from another thread you have to use the Form.Invoke method.

Brad Semrad
  • 1,501
  • 1
  • 11
  • 19
  • 1
    or BeginInvoke - if you don't want the calling thread to wait for the form to update (post it onto the UI thread) – Jeb Jan 13 '12 at 19:52
0

You can't update the UI from a thread other than the UI thread. You need to delegate the action back over. Try using the Invoke() method provided on controls, or even the form itself.

0

If you are on WPF, you have to call into the UI thread with the Application's Dispatcher object:

Application.Current.Dispatcher.BeginInvoke(() =>
{
   UndoButton.Enabled = _undoBuffer.CanUndo;
});
Steve Danner
  • 21,818
  • 7
  • 41
  • 51
  • I m getting error saying no definition for Current – jprbest Jan 13 '12 at 20:16
  • You are using System.Windows.Application and not System.Windows.Forms.Application right? If you're not in a WPF app, then Brad's answer is more suitable. – Steve Danner Jan 13 '12 at 20:20
  • Something must be off here, because System.Windows.Application absolutely has a static Current member: http://msdn.microsoft.com/en-us/library/system.windows.application.current.aspx – Steve Danner Jan 13 '12 at 20:43