Welcome to OGeek Q&A 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 Reply

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);
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...