最近在项目中要用到子线程运行结束向主线程通知的需求,利用线程上下文来实现线程之间的同步。
子线程结束后调用同步函数,向主线程发送时间字符串,改变主窗体的label标签
label标签改变事件触发处理函数,进行显示;
代码如下:
主窗体:
public static MainForm comMainForm; //其他类可以直接调用此窗体的控件
public MainForm()
{
InitializeComponent();
comMainForm = this;
}
//任务中心标签内容发生更新事件响应
private void taskFreshFlag_TextChanged(object sender, EventArgs e)
{
labResult.Visible = true;
labResult.Text = DateTime.Now.TimeOfDay.ToString();
}
工具类:
public class WebServiceConnect
{
private static SynchronizationContext mainThreadSynContext;
//此处修改为异步获取任务方式
public static void GetTaskInfo(string taskInfoIn0)
{
mainThreadSynContext = SynchronizationContext.Current; //当前线程上下文
taskThread = new Thread(new ParameterizedThreadStart(webConnect));
taskThread.Start(taskInfoIn0);
}
//回调函数
private static void CallBack(object state)
{
//主线程报告信息
MainForm.comMainForm.taskFreshFlag.Text = "task" + DateTime.Now.TimeOfDay.ToString();
}
public static void webConnect(object taskInfoIn)
{
try
{
string taskInfoIn0 = taskInfoIn.ToString();
circle = false;
}
catch (Exception ex)
{
System.Net.WebException wex = ex as System.Net.WebException;
if (connCount > 1)
{
circle = false;
taskThread.Abort();
System.Windows.Forms.MessageBox.Show("通讯未连接!");
return;
}
}
mainThreadSynContext.Post(new SendOrPostCallback(CallBack), null); //通知主线程
}