多线程,异步委托,同步委托几种方式的区别
Code
public delegate void DoThingsDelegate();
private void Window_Loaded(object sender, RoutedEventArgs e)
{
//通过子线程调用方法 按钮事件可以执行
Thread a = new Thread(new ThreadStart(DoSomeThing));
a.IsBackground = true;
a.Start();
//虽然是异步委托 但是按钮根本就显示不出来
DoThingsDelegate dothingsEvent = new DoThingsDelegate(DoSomeThing);
IAsyncResult result = dothingsEvent.BeginInvoke(null, null);
dothingsEvent.EndInvoke(result);
//同步委托就更不行了
dothingsEvent.Invoke();
//真正的异步委托 异步调用方法,与多线程相似
IAsyncResult result = dothingsEvent.BeginInvoke(new AsyncCallback(DoThingEnd), null);
}
public static void DoSomeThing()
{
Console.WriteLine("begin");
Thread.Sleep(6000);
Console.WriteLine("end");
}
public static void DoThingEnd(IAsyncResult result)
{
Console.WriteLine("end it");
}
private void button1_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("11111");
}
public delegate void DoThingsDelegate();
private void Window_Loaded(object sender, RoutedEventArgs e)
{
//通过子线程调用方法 按钮事件可以执行
Thread a = new Thread(new ThreadStart(DoSomeThing));
a.IsBackground = true;
a.Start();
//虽然是异步委托 但是按钮根本就显示不出来
DoThingsDelegate dothingsEvent = new DoThingsDelegate(DoSomeThing);
IAsyncResult result = dothingsEvent.BeginInvoke(null, null);
dothingsEvent.EndInvoke(result);
//同步委托就更不行了
dothingsEvent.Invoke();
//真正的异步委托 异步调用方法,与多线程相似
IAsyncResult result = dothingsEvent.BeginInvoke(new AsyncCallback(DoThingEnd), null);
}
public static void DoSomeThing()
{
Console.WriteLine("begin");
Thread.Sleep(6000);
Console.WriteLine("end");
}
public static void DoThingEnd(IAsyncResult result)
{
Console.WriteLine("end it");
}
private void button1_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("11111");
}