1

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.

Marlon
  • 19,924
  • 12
  • 70
  • 101
user1161828
  • 13
  • 1
  • 3
  • possible duplicate of [Threading issue "The calling thread cannot access this object because a different thread owns it". Any solutions?](http://stackoverflow.com/questions/7684206/threading-issue-the-calling-thread-cannot-access-this-object-because-a-differen) – JasonMArcher Jul 08 '14 at 17:02

1 Answers1

2

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.

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300