多线程更新主表单



我有一个应用程序(frmMain),它调用一个类(ThreadBL),它启动2个线程(Thread1, Thread2)。当Thread1执行操作时,我希望能够将更新发送回frmMain,类似地,Thread2也会这样做。

这里是一些切碎的代码,基本上是如何工作的。我没有机会测试这个特定的代码是否有效,但是当我运行我拥有的原始代码时,我得到了一个"跨线程操作无效"的错误。

是否有更好的方法从线程更新frmMain ?这段代码是否过于详尽和不必要?如有任何反馈,我们将不胜感激。

public class ThreadExample() {
  private void ThreadExample() {};
  public delegate void CurrentFileProcessing(string filename);
  public event CurrentFileProcessing CurrentFileProcessingEvent;
  public bool startCopying() {
    CurrentFileProcessingEvent += new CurrentFileProcessing(handlerCurrentFileProcessing);
    copyFiles();
    return true;
  }
  public void copyFiles() {
    CurrentFileProcessingEvent("Copying: file.xml");
  }
  private void handlerCurrentFileProcessing(string filename) {
    Console.WriteLine("Processing: " + filename);
  }
}
public class ThreadBL() {
  private void ThreadBL() {};
  public delegate void Thread1CurrentProcessing(string filename);
  public delegate void Thread2CurrentProcessing(string filename);
  public event Thread1CurrentProcessing Thread1CurrentProcessingEvent;
  public event Thread2CurrentProcessing Thread2CurrentProcessingEvent;
  private bool processingThread1 = false;
  private bool processingThread2 = false;
  public void processThreads() {
    BackgroundWorker thread1BW = new BackgroundWorker();
    thread1BW.DoWork += new DoWorkEventHandler(thread1Process);
    thread1BW.RunWorkerCompleted += new RunWorkerCompletedEventHandler(completeThread1);
    thread1BW.RunWorkerAsync();
    while (!processingThread1) {
      Console.WriteLine("Waiting for thread1 to finish. TID: " + Thread.CurrentThread.ManagedThreadId);
      Thread.Sleep(100);
    }
    BackgroundWorker thread2BW = new BackgroundWorker();
    thread2BW.DoWork += new DoWorkEventHandler(thread2Process);
    thread2BW.RunWorkerCompleted += new RunWorkerCompletedEventHandler(completeThread2);
    thread2BW.RunWorkerAsync();
    while (!thread2Done) {
      Console.WriteLine("Waiting for thread2 to finish. TID: " + Thread.CurrentThread.ManagedThreadId);
      Thread.Sleep(100);
    }
  }
  private void thread1Process() {
    ThreadExample thread1Example = new ThreadExample();
    thread1Example.CurrentFileProcessingEvent += new ThreadExample.CurrentFileProcessing(handlerThread1CurrentProcessingEvent);
    processingThread1 = thread1Example.startCopying();
  }
  private void completeThread1(object sender, RunWorkerCompletedEventArgs e) {
    Console.WriteLine("Completed Thread1. TID: " + Thread.CurrentThread.ManagedThreadId);
    processingThread1 = true;
  }
  private void thread2Process() {
    ThreadExample thread2Example = new ThreadExample();
    thread2Example.CurrentFileProcessingEvent += new ThreadExample.CurrentFileProcessing(handlerThread2CurrentProcessingEvent);
    processingThread2 = thread2Example.startCopying();
  }
  private void completeThread2(object sender, RunWorkerCompletedEventArgs e) {
    Console.WriteLine("Completed Thread1. TID: " + Thread.CurrentThread.ManagedThreadId);
    processingThread2 = true;
  }
  private void handlerThread2CurrentProcessingEvent(string filename) {
    Console.WriteLine("Thread2 Processing: " + filename);
    Thread2CurrentProcessingEvent(filename);
  }
}
public class frmMain {
  private ThreadBL threadBL = new ThreadBL();
  public void frmMain() {
    threadBL.Thread1CurrentProcessingEvent += new ThreadExample.CurrentFileProcessing(handlerThread1ProgressEvent);
    threadBL.Thread2CurrentProcessingEvent += new ThreadExample.CurrentFileProcessing(handlerThread2ProgressEvent);
    threadBL.processThreads();
  }
  private void handlerThread1ProgressEvent(string progress) {
    lblCopyingProgress.Invoke(new MethodInvoker(delegate { lblCopyingProgress.Text = progress; }));
    this.Refresh();
  }
  private void handlerThread2ProgressEvent(string progress) {
    lblCopyingProgress.Invoke(new MethodInvoker(delegate { lblCopyingProgress.Text = progress; }));
    this.Refresh();
  }
}

在主线程上调用的最好方法是调用Control.Invoke(…)或Control.BeginInvoke(…)。前者将阻塞,直到主线程处理调用。后者只会在主线程空闲时发布调用,等待处理。

如果你不想让你的线程知道Control类型,你可以简单地把Invoke和BeginInvoke调用包装到你自己的接口中,比如IInvoker,并声明你的主表单来实现它。把这个接口作为你的线程的参数,你就可以开始了。

对于执行线程工作,我建议使用ThreadPool。我会这样做(假设所有方法都在主表单的代码中)。
private void MyThread(object param)
{
   MyForm form = (MyForm) param; // pass your form as your param
   DoWork(); // Whatever it is you are doing on your thread
   form.Invoke(new MethodInvoker(form.NotifyComplete)); // Invokes on main thread
}
public void Button_OnClick(object sender, EventArgs args)
{
   ThreadPool.QueueUserWorkItem(new Action<object>(MyThread), this);
}

private void NotifyComplete()
{
   // update your controls here
   ...
}

相关内容

  • 没有找到相关文章