QueryRecord()是一个比较耗时间的方法,而且最终要讲结果显示到TextBox上面。在结果显示在控件上之前,界面处于卡死状态,本人找了很久,最终发现要使用Invoke方法。
private void QueryRecod(string SN, int sponsor, TextBox textShow)
{
if (SN == "")
{
MessageBox.Show("PCB码不能为空!");
return;
}
string strSponse = string.Empty;
Bobcat queryPCB = new Bobcat();//实例化一个对象
int reNum = (queryPCB.QuerySfsServerInfo(sponsor, SN, out strSponse));//调用方法;
List<string> list = new List<string>();//不能使用string[],因为Invoke()方法中参数只会传递stirng[0],stirng[1]、string[2]后续不会传递,结果报错
list.Add(SN);//添加数据
list.Add(strSponse);
if (reNum == 1)
{
**if (textShow.InvokeRequired)//判断是否要跨线程**
{
textShow.Invoke(new Action<List<string>>((s) =>**//防止跨线程报错,并且防止界面卡死
{
List<string>** strMes = s as List<string>;
textShow.Clear();
textShow.Text = "[SN]" + strMes[0] + ":查询失败!" + "\n" + "返回信息:" + strMes[1];
}), list);
}**
}
else if (reNum == 0)
{
if (textShow.InvokeRequired)
{
textShow.Invoke(new Action<List<string>>((s) =>
{
List<string> strMes = s as List<string>;
textShow.Clear();
textShow.Text = "[SN]" + strMes[0] + ":查询成功!" + "\n" + "返回信息:" + strMes[1];
}), list);
}
}
if (reNum == -1)
{
if (textShow.InvokeRequired)
{
textShow.Invoke(new Action<List<string>>((s) =>
{
List<string> strMes = s as List<string>;
textShow.Clear();
textShow.Text = "[SN]" + strMes[0] + ":网络连接超时,请检查网络是否连接!" ;
}),list);
}
}
}
下面是使用一个按钮调用,且使用了后台线程:
ArrayList list = new ArrayList();//把要传递给方法的数据打包
list.Add(textPCB.Text.Trim());//添加SN
list.Add(0);//sponssor(0:表示查询过站信息)
list.Add(textMessage);
Thread objThread = new Thread((s) =>
{
ArrayList list1 = s as ArrayList;//把传递过来的数据从object类型转化为ArrayList;
string SN = list1[0] as string;
int sponsor = (int)list1[1];
TextBox textShow = list1[2] as TextBox;
QueryRecod(SN, sponsor, textShow);
});
objThread.IsBackground = true;
objThread.Start(list);//表示线程可以开始