Thread problem in Backgroundworker

Asked

Viewed 38 times

-1

I’m learning how to use Backgroundworker now and I’m having this problem to access the information of some chekbox on Mainwindow, I’ve been researching about Dispatcher but I can’t quite understand how to implement it here. "The call thread cannot access this object because it belongs to a different thread"

private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            var worker = sender as BackgroundWorker;
            
            
             //ERRO AQUI
            if (check1.IsChecked == true)
            {
                qualidades.Add(1);
            }
            if (check2.IsChecked == true)
            {
                qualidades.Add(2);
            }
            if (check3.IsChecked == true)
            {
                qualidades.Add(3);
            }
            if (check4.IsChecked == true)
            {
                qualidades.Add(4);
            }
            if (check5.IsChecked == true)
            {
                qualidades.Add(5);
            }
            #endregion
            
                }

1 answer

0

You can place access to the controls within a context that is synchronized with the UI Thread.

          Dispatcher.BeginInvoke(new Action(() =>  
           {  
            if (check1.IsChecked == true)
            {
               qualidades.Add(1);
            }
            if (check2.IsChecked == true)
            {
                qualidades.Add(2);
            }
            if (check3.IsChecked == true)
            {
                qualidades.Add(3);
            }
            if (check4.IsChecked == true)
            {
                qualidades.Add(4);
            }
            if (check5.IsChecked == true)
            {
                qualidades.Add(5);
            } 
           }), DispatcherPriority.Background);  

More details here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.