Sunday, April 3, 2011

Threading problem in WPF

Hi all,

I'm getting this Exception

System.InvalidOperationException was unhandled by user code Message="The calling thread cannot access this object because a different thread owns it."

whenever I run the following code

public partial class MainScreen : Window
{
        Timer trm;

        public MainScreen()
        {
            InitializeComponent();

            trm = new Timer(1000);
            trm.AutoReset = true;
            trm.Start();
            trm.Elapsed += new ElapsedEventHandler(trm_Elapsed);
        }

        void trm_Elapsed(object sender, ElapsedEventArgs e)
        {
            lblTime.Content = System.DateTime.Now;
        }
}

guys any solution... I badly wann come out of it :(

From stackoverflow
  • Any time you modify Windows controls you must do so on the UI thread (the one that created the controls).

    See this question for lots of details.

  • Use DispatcherTimer instead:

    public partial class MainScreen : Window{
    DispatcherTimer tmr;    
    public MainScreen() {
    InitializeComponent();
    tmr = new DispatcherTimer();
    tmr.Tick += new EventHandler(tmr_Tick);
    tmr.Start();    
    }
    void tmr_Tick(object sender, EventArgs e) {
        lblTime.Content = System.DateTime.Now;
    }
    }
    
  • To be short, you should use Dispatcher.Invoke method to update UI elements.

0 comments:

Post a Comment