在C#中跨线程访问Winform控件
在程序需要读取CAD文件列表中的文件信息,这是一个非常费时的操作,所以希望通过多线程的方式来实现,并且可以随时中止。由于初次使用多线程,开始的时候采用独立的线程类,该类返回数据,在Thread.Join()方法等待线程结束后写入数据到窗体控件中,结果和单线程没有什么区别;后来查看资料通过使用MethodInvoker解决了这一问题,但是对于线程处理还是概念非常模糊,大家谁有这方面的心得、资料等共享学习学习。
public partial class frmMain : Form
{
private volatile bool _stoped = false;
private void btFilter_Click(object sender, EventArgs e)
{
_stoped = false;
Thread t = new Thread(new ThreadStart(StartNewThread));
t.Start();
}
private void btStop_Click(object sender, EventArgs e)
{
_stoped = true;
}
private void GetFileSize()
{
btFilter.Enabled = false;
using (AutoCADConnector CAD = new AutoCADConnector())
{
foreach (ListViewItem t in lvSource.Items)
{
if (!_stoped)
{
AutoCAD.AcadDocument doc = CAD.Application.Documents.Open(t.SubItems[2].Text, true, "");
double[] p1 = new double[] { 0, 0, 0 }; //右上角坐标
double[] p2 = new double[] { 0, 0, 0 }; //左下角坐标
double scale = 0; //缩放比例
p1 = (double[])doc.GetVariable("EXTMAX");
p2 = (double[])doc.GetVariable("EXTMIN");
scale = Convert.ToDouble(doc.GetVariable("DIMSCALE"));
double w = Math.Ceiling((p1[0] - p2[0]) / scale);
double h = Math.Ceiling((p1[1] - p2[1]) / scale);
doc.Close(false, "");
t.SubItems[1].Text = string.Format("{0}*{1} {2}", w, h, scale);
//lvSource.Refresh();
//Thread.Sleep(100);
Application.DoEvents();
}
else
break;
}
}
btFilter.Enabled = true;
}
private void StartNewThread()
{
MethodInvoker me = new MethodInvoker(this.GetFileSize);
this.BeginInvoke(me);
}
}
{
private volatile bool _stoped = false;
private void btFilter_Click(object sender, EventArgs e)
{
_stoped = false;
Thread t = new Thread(new ThreadStart(StartNewThread));
t.Start();
}
private void btStop_Click(object sender, EventArgs e)
{
_stoped = true;
}
private void GetFileSize()
{
btFilter.Enabled = false;
using (AutoCADConnector CAD = new AutoCADConnector())
{
foreach (ListViewItem t in lvSource.Items)
{
if (!_stoped)
{
AutoCAD.AcadDocument doc = CAD.Application.Documents.Open(t.SubItems[2].Text, true, "");
double[] p1 = new double[] { 0, 0, 0 }; //右上角坐标
double[] p2 = new double[] { 0, 0, 0 }; //左下角坐标
double scale = 0; //缩放比例
p1 = (double[])doc.GetVariable("EXTMAX");
p2 = (double[])doc.GetVariable("EXTMIN");
scale = Convert.ToDouble(doc.GetVariable("DIMSCALE"));
double w = Math.Ceiling((p1[0] - p2[0]) / scale);
double h = Math.Ceiling((p1[1] - p2[1]) / scale);
doc.Close(false, "");
t.SubItems[1].Text = string.Format("{0}*{1} {2}", w, h, scale);
//lvSource.Refresh();
//Thread.Sleep(100);
Application.DoEvents();
}
else
break;
}
}
btFilter.Enabled = true;
}
private void StartNewThread()
{
MethodInvoker me = new MethodInvoker(this.GetFileSize);
this.BeginInvoke(me);
}
}