2010-11-17 76 views
0

我就是这样的。它给了我错误。我删除了所有不需要的代码部分。它给我这个错误两条线程之间的沟通

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

public partial class MainWindow : Window 
{ 
    BackgroundWorker worker; 
    Grafik MainGrafik; 

    double ProgressBar 
    { 
     set { this.progressBarMain.Value = value; } 
    } 

    public MainWindow() 
    { 
     InitializeComponent(); 
     worker = new BackgroundWorker(); 
     worker.DoWork += new DoWorkEventHandler(worker_DoWork); 

     MainGrafik = new Grafik(); 
     MainGrafik.ProgressUpdate += 
      new Grafik.ProgressUpdateDelegate(MainGrafik_ProgressUpdate); 

     worker.RunWorkerAsync(); 
    } 

    void MainGrafik_ProgressUpdate(double progress) 
    { 
     ProgressBar = progress; 
    } 


    void worker_DoWork(object sender, DoWorkEventArgs e) 
    { 
     while(true) 
     { 
      MainGrafik.Refresh(); 
      Thread.Sleep(2000); 
     } 
    } 
} 

class Grafik 
{ 
    public delegate void ProgressUpdateDelegate(double progress, 
     DateTime currTime); 
    public event ProgressUpdateDelegate ProgressUpdate; 

    public void Refresh() 
    { 
      ProgressUpdate(5); // Just for testing 
    } 
} 
+0

如果要举报你可以使用进度[ 'BackGroundWorker.ReportProgress'](http://msdn.microsoft.com/en-us/library/ka89zff4.aspx)。 – 2010-11-17 20:03:59

回答

8

您无法更新从另一个线程的UI对象。他们必须在UI线程中更新。尝试将此代码添加到MainGrafik_ProgressUpdate(双进程)

void MainGragfik_ProgressUpdate(double progress) 
{ 
    if (InvokeRequired) 
    { 
     BeginInvoke((MethodIvoker)(() => 
     { 
      MainGragfik_ProgressUpdate(progress); 
     })); 

     return; 
    } 

    ProgressBar = progress; 
} 
0

触发ProgressUpdate事件的线程是您的BackgroundWorker。 ProgressUpdate事件处理程序可能在该线程上运行,而不是UI线程。

0
在你的其他线程的执行上下文的形式在短时间内调用此

void MainGrafik_ProgressUpdate(object sender, EventArgs e) { 
    Action<T> yourAction =>() yourAction;    

    if(yourForm.InvokeRequired) 
     yourForm.Invoke(yourAction); 
    else yourAction; 

    } 

或用MethodInvoker(空白代表)

void MainGrafik_ProgressUpdate(object sender, EventArgs e) { 
    MethodInvoker invoker = delegate(object sender, EventArgs e) { 

     this.ProgressBar = whatever progress; 
    };   


    }