最近需要做一个窗体中实时调用类中的一个线程问题,在网上找了很多都不符合需求,终于搞定这个问题,Mark一下要不然时间久了就忘记了~
MainWindow:
Class1 oid = new Class1();
public MainWindow()
{
InitializeComponent();
oid.show += C_show;
}
public void C_show(string d)
{
try{
this.Dispatcher.Invoke(new Action(() =>
{MessageBox.Show(d); }));
}catch{}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
oid.demo();
}
Class1:
public delegate void Exe( string check); //委托---将类中的线程数据传回主窗体下
public event Exe show;
int i = 0;
/// <summary>
/// 开启获取数据线程
/// </summary>
public void demo()
{
var th1=new Thread(()=>
{
while (true){
show(i++.ToString());}});
th1.SetApartmentState(ApartmentState.STA);
th1.IsBackground = true;
th1.Start();
}