views:

99

answers:

3

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 :(

A: 

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.

DocMax
+3  A: 

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;
}
}
Stanislav Kniazev
A: 

To be short, you should use Dispatcher.Invoke method to update UI elements.

Methos