简体   繁体   中英

Method doesn't return controlling

I have a grid on WPF form and another class, that has some events. From my wpf form i subscribe on those events and i want them to add some objects to my grid, but only that i have is "The calling thread cannot access this object because a different thread owns it." How can I avoid this proble and get same functionality?

This has been covered ad nauseam on StackOverflow and elsewhere. You need to use the Dispatcher to marshal your access back to the UI thread. For example:

private void OnSomeEvent(object sender, EventArgs e)
{
    // this is being called on a thread other than the UI thread so marshal back to the UI thread
    Dispatcher.BeginInvoke((ThreadStart)delegate
    {
        // now the grid can be accessed
        grid.Whatever = foo;
    });
}

This is a cross-threading issue. Look into delegate creation so you can safely invoke another thread to modify something that was created on the different thread. Here is a good MSDN article about how to make these thread-safe calls.

http://msdn.microsoft.com/en-us/library/ms171728(v=vs.80).aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM