我找到了解决方案here:基本上,它将表单控件传递给类构造函数,然后在该类内部使用form.Invoke从窗体UI线程触发事件。
类:
using System;
using System.Windows.Forms;
using System.Threading;
namespace ThreadTest
{
public class WorkerClass
{
private Thread thr;
// UI control for update
public Control UIControl { get; set; }
public delegate void StatusUpdate(DateTime dateTime, string message);
public event StatusUpdate OnStatusUpdate;
// Starts thread
public void Start()
{
thr = new Thread(new ThreadStart(MainWorker));
thr.Start();
}
// Main thread worker
public void MainWorker()
{
int i = 0;
while (true)
{
string message = string.Format("Value of i={0}", i++);
FireStatusUpdate(DateTime.Now, message);
Thread.Sleep(1000);
}
}
// Fire thread safe event
private void FireStatusUpdate(DateTime dateTime, string message)
{
// UIControl is set and OnStatusUpdate has subscriber
if (UIControl != null && OnStatusUpdate != null)
{
if (UIControl.InvokeRequired)
{
UIControl.Invoke(new StatusUpdate(FireStatusUpdate),
new object[] { dateTime, message });
return;
}
OnStatusUpdate(dateTime, message);
}
}
}
}
FORM:
using System;
using System.Drawing;
using System.Windows.Forms;
namespace ThreadTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
WorkerClass worker = new WorkerClass();
// add event handler
worker.OnStatusUpdate += new WorkerClass.StatusUpdate(worker_OnStatusUpdate);
// add UI control to invoke
worker.UIControl = this;
worker.Start();
}
void worker_OnStatusUpdate(DateTime dateTime, string message)
{
label1.Text = dateTime.ToLongTimeString();
label1.Text += " " + message;
}
}
就我而言,我已经改变了事件的类型,从StatusUpdate到
EventHandler<MyEventArgs>
,是MyEventArgs这个类:
public class MyEventArgs : EventArgs
{
public string MyString { get; set; }
}
谢谢!
谢谢!我没有明确地使用工作线程,我只是实例化包含引发事件的本地对象的类,然后从该类中提出我自己的事件,并将其捕获到表单中。 我与Compact Framework的3.5工作,不具有的SynchronizationContext功能。 我试图用这个[执行](http://www.planetgeek.ch/2009/02/03/part-i-mimic-synchronizationcontext-behaviour-on-net-cf/) 但它没由于该示例没有实现.Current成员,因此不起作用。 我想我需要另一种方法... – Roger 2014-10-08 10:36:06
如果实施例没有实现.Current成员为什么不使用类的实例,如'syncContext = SynchronizationContext'?您可以查看的另一个选项是http://nitoasync.codeplex.com/。 – groverboy 2014-10-08 23:36:12