The calling thread cannot access this object because a different thread owns it

為{幸葍}努か 提交于 2019-12-30 22:53:58

问题


namespace PizzaSoftware.UI
{
    /// <summary>
    /// Interaction logic for LoginForm.xaml
    /// </summary>
    public partial class LoginForm : Window
    {
        public LoginForm()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Timer timer = new Timer(1000);
            timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
            timer.Enabled = true;
        }

        void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            lblCurrentTime.Content = DateTime.Now.ToShortTimeString();
        }
    }
}

Basically, I'm just trying to have a label on my form that displays the current time. I'm using a Timer as suggested in another of my SO question.

I'm receiving the error in title. What can I do to solve this?


回答1:


Well, the simplest approach is to use a DispatcherTimer - which will fire its Tick event in the dispatcher thread:

DispatcherTimer timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromMilliseconds(1000);
timer.IsEnabled = true;
timer.Tick += timer_Elapsed;

Alternatively, you can use Dispatcher.Invoke/BeginInvoke to execute a delegate in the dispatcher thread... but that will be more complicated. This would be a better approach if you needed to do significant work on each timer tick and then just update the UI with the result - but as you're not doing much work at all here, it's fine to just do it all in the UI thread.




回答2:


Didn't realize this was a WPF app. You need to get a hold of the Dispatcher, which you can do in the Constructor:

    private Dispatcher _dispathcer;

    public LoginForm()
    {
        InitializeComponent();
        _dispathcer = Dispathcer.CurrentDispather;
    }



    void timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        _dispathcer.Invoke(new Action( ()=> { lblCurrentTime.Content = DateTime.Now.ToShortTimeString();});
    }


来源:https://stackoverflow.com/questions/5423422/the-calling-thread-cannot-access-this-object-because-a-different-thread-owns-it

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!