Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.4k views
in Technique[技术] by (71.8m points)

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

i have a problem whenever i Refresh the prograss bar i get the error The calling thread cannot access this object because a different thread owns it how can i remove it shashank

     backgroundWorker12 = new BackgroundWorker();
     timer1.Enabled = true;
      //cancel any async processes running for the background worker
     //backgroundWorker1.CancelAsync();
     backgroundWorker12.DoWork += (s, args) =>
     {

         BackgroundWorker worker2 = s as BackgroundWorker;
         worker2.WorkerReportsProgress = true;

         float percentageDone = 20f;
         //check if the user status and update the password in xml
         CheckUseridPwd();


         //call the function to sync the wall chart data

         //call the function to sync event relate data

         percentageDone = 100f;
         ValidateLogin2(txtUserID.Text.Trim(), txtPassword.Password.Trim(), -1); 
         worker2.ReportProgress((int)percentageDone);

     };`
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This bit looks like it's using UI controls from the wrong thread:

 ValidateLogin2(txtUserID.Text.Trim(), txtPassword.Password.Trim(), -1);

I suggest you capture the user and password in local string variables above the code which adds the event handler - you can use those captured variables within your delegate. That way everything should be on the right thread:

backgroundWorker12 = new BackgroundWorker();
timer1.Enabled = true;

string user = txtUserID.Text.Trim();
string password = txtPassword.Password.Trim();
backgroundWorker12.DoWork += (s, args) =>
{
    // ... same code as before up to here
    ValidateLogin2(user, password, -1); 
    worker2.ReportProgress((int)percentageDone);
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...