“调用线程无法访问该对象,因为不同的线程拥有它。”与 Twitterizer

发布于 2024-12-27 22:44:36 字数 637 浏览 2 评论 0原文

我正在 WPF 中开发一个 twitter 客户端,我想使用后台工作者来更新推文,但结果出现此错误消息“调用线程无法访问此对象,因为不同的线程拥有它”。

public NewTweet()
{
    InitializeComponent();

    this.MouseLeftButtonDown += (o, e) => DragMove();
    worker.WorkerReportsProgress = true;
    worker.DoWork += DoWork;
    worker.RunWorkerCompleted += WorkerCompleted; 
}

void DoWork(object sender, DoWorkEventArgs e)
{
    TwitterResponse<TwitterStatus> tweetResponse = TwitterStatus.Update(token, txttweet.Text);
    System.Threading.Thread.Sleep(5);
}

private void button1_Click(object sender, RoutedEventArgs e)
{
    worker.RunWorkerAsync(); 
}

非常感谢。

i'm developing a twitter client in WPF and i want to use a backgroundworker to update a tweet, but results this error message "The calling thread cannot access this object because a different thread owns it".

public NewTweet()
{
    InitializeComponent();

    this.MouseLeftButtonDown += (o, e) => DragMove();
    worker.WorkerReportsProgress = true;
    worker.DoWork += DoWork;
    worker.RunWorkerCompleted += WorkerCompleted; 
}

void DoWork(object sender, DoWorkEventArgs e)
{
    TwitterResponse<TwitterStatus> tweetResponse = TwitterStatus.Update(token, txttweet.Text);
    System.Threading.Thread.Sleep(5);
}

private void button1_Click(object sender, RoutedEventArgs e)
{
    worker.RunWorkerAsync(); 
}

thank you very much.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

朦胧时间 2025-01-03 22:44:36

如果您尝试直接从 DoWork 方法内部更新 UI 元素,您将收到此错误。

要报告进度,您应该使用BackgroundWorker.ReportProgress 方法。然后,在您的 UI 中,订阅 BackgroundWorker.ProgressChanged 事件。这将确保进度更新被编组到正确的线程上。您不应直接从 DoWork 内部更新 UI 元素。

You will get this error if you try to update UI elements directly from inside the DoWork method.

To report progress, you should use the BackgroundWorker.ReportProgress method. Then, in your UI, subscribe to the BackgroundWorker.ProgressChanged event. This will ensure that the progress update gets marshalled onto the correct thread. You should not update UI elements directly from inside DoWork.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文