c# 子线程与主线程通信二
之前写过使用线程上下文实现线程同步,今天利用子线程向主线程发送事件,实现子线程与主线程的同步
基本步骤
1、定义类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DX_equip.Class
{
/// <summary>
/// 定义一个信息委托
/// </summary>
/// <param name="sender">发布者</param>
/// <param name="msg">发送内容</param>
public delegate void DxMsgDlg(object sender,object msg);
public class DxMessageHelper
{
/// <summary>
/// 消息发送事件
/// </summary>
public static event DxMsgDlg EventSend;
public static void DxSendMessage(object sender, object msg)
{
if (EventSend != null)//
{
EventSend(sender, msg);
}
}
}
}
2、在子线程中发送事件,实现事件通知功能
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;
using System.Xml;
using System.Data;
using System.Windows.Forms;
namespace DX_equip.Class
{
public class WebServiceConnect
{
private static bool circle = false;
private static Thread taskThread;
public static string getTaskMsg = "";
public static int connCount = 0;
private static SynchronizationContext mainThreadSynContext;
public static void GetTaskInfo(string taskInfoIn0)
{
mainThreadSynContext = SynchronizationContext.Current;
taskThread = new Thread(new ParameterizedThreadStart(webConnect));
taskThread.Start(taskInfoIn0);
}
public static void webConnect(object taskInfoIn)
{
getTaskMsg = "";
try
{
string taskInfoIn0 = taskInfoIn.ToString();
TestWebReference.TDMTestTaskInterfaceServiceService taskInfoService = new TestWebReference.TDMTestTaskInterfaceServiceService();
string taskName = SystemInfoClass.systemBaseInfo.taskName;
getTaskMsg = taskInfoService.queryTaskInfo(taskInfoIn0, taskName);
StackTrace st = new StackTrace();
string callName = st.GetFrame(1).GetMethod().Name;
DxMessageHelper.DxSendMessage(callName,getTaskMsg);
}
catch (Exception ex)
{
System.Net.WebException wex = ex as System.Net.WebException;
System.Windows.Forms.MessageBox.Show("通ª¡§讯?未¡ä连¢?接¨®!ê?");
}
}
3、接收事件函数中注册事件
public MainForm()
{
InitializeComponent();
DxMessageHelper.EventSend += new DxMsgDlg(Receive_DxEventSend);
}
private void Receive_DxEventSend(object sender, object msg)
{
this.Invoke(new Action(() =>
{
labTaskMsg.Visible = true;
labTaskMsg.Text = msg.ToString();
}));
Trace.WriteLine("***Info*** " + msg.ToString());
}