C # child thread and the main thread communication method

Recent use to inform the child thread needs to run to the end of the main thread by thread context to achieve synchronization between threads in the project.

After calling the sub-thread synchronization function, the transmission time string to the main thread, the main form of the label should change

label label changes trigger event handler, display;

code show as below:

The main form:

public static MainForm comMainForm; // Other classes can call this form of direct control

public MainForm()
{
InitializeComponent();
comMainForm = this;
}

// central task tag content update event occurs in response
Private void taskFreshFlag_TextChanged (SENDER Object, EventArgs E)
{
labResult.Visible = to true;
labResult.Text DateTime.Now.TimeOfDay.ToString = ();
}

 

Tools:

public class WebServiceConnect
{

  private static SynchronizationContext mainThreadSynContext;

// This modified embodiment is an asynchronous task acquired
public static void getTaskInfo (String taskInfoIn0)
{
  mainThreadSynContext = SynchronizationContext.Current; // current thread context
  taskThread the Thread new new = (new new ParameterizedThreadStart (WebConnect));
  taskThread.Start (taskInfoIn0);
}

// callback
Private static void the CallBack (State Object)
{
// main thread report information
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); //通知主线程
}

Guess you like

Origin www.cnblogs.com/xihong2014/p/10953210.html