C# BeginInvoke EndInvoke
如遇到以下两种需求时,可以试试 BeginInvoke 方法
1.某些时候需要开线程处理,需要主线程子线程配合完成
1-1.投票
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace InvokeTest { class Program { static int TakeAWhile(int data, int SleepMillionSeconds) { Console.WriteLine("TakesAWhile started"); Thread.Sleep(SleepMillionSeconds); Console.WriteLine("TakesAWhile end"); return ++data; } public delegate int TakesAWhileDelegate(int data, int SleepMillionSeconds); static void Main(string[] args) { TakesAWhileDelegate d1 = TakeAWhile; IAsyncResult asyncResult = d1.BeginInvoke(1, 3000, null, null); while(!asyncResult.IsCompleted) { //异步未完成,主线程执行 Console.WriteLine("."); Thread.Sleep(500); } int result = d1.EndInvoke(asyncResult); Console.WriteLine("result: {0}", result); Console.ReadKey(); } } }
结果:
1-2.等待句柄
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace InvokeTest { class Program { static int TakeAWhile(int data, int SleepMillionSeconds) { Console.WriteLine("TakesAWhile started"); Thread.Sleep(SleepMillionSeconds); Console.WriteLine("TakesAWhile end"); return ++data; } public delegate int TakesAWhileDelegate(int data, int SleepMillionSeconds); static void Main(string[] args) { TakesAWhileDelegate d1 = TakeAWhile; IAsyncResult asyncResult = d1.BeginInvoke(1, 3000, null, null); while(true) { //异步未完成,主线程执行 Console.WriteLine("."); if(asyncResult.AsyncWaitHandle.WaitOne(500, false)) { Console.WriteLine("Can get the result now."); break; } } int result = d1.EndInvoke(asyncResult); Console.WriteLine("result: {0}", result); Console.ReadKey(); } } }
结果:
1-3.回调函数
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace InvokeTest { class Program { static int TakeAWhile(int data, int SleepMillionSeconds) { Console.WriteLine("TakesAWhile started"); Thread.Sleep(SleepMillionSeconds); Console.WriteLine("TakesAWhile end"); return ++data; } static void TakeAWhileComplete(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException("asyncResult"); TakesAWhileDelegate d1 = asyncResult.AsyncState as TakesAWhileDelegate; Trace.Assert(d1 != null, "Invalid object type"); int result = d1.EndInvoke(asyncResult); Console.WriteLine("result: {0}", result); } public delegate int TakesAWhileDelegate(int data, int SleepMillionSeconds); static void Main(string[] args) { TakesAWhileDelegate d1 = TakeAWhile; d1.BeginInvoke(1, 3000, TakeAWhileComplete, d1); for(int i = 0; i < 15; i++) { //异步未完成,主线程执行 Console.WriteLine("."); Thread.Sleep(500); } Console.ReadKey(); } } }
结果:
Lambda表达式写法
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace InvokeTest { class Program { static int TakeAWhile(int data, int SleepMillionSeconds) { Console.WriteLine("TakesAWhile started"); Thread.Sleep(SleepMillionSeconds); Console.WriteLine("TakesAWhile end"); return ++data; } public delegate int TakesAWhileDelegate(int data, int SleepMillionSeconds); static void Main(string[] args) { TakesAWhileDelegate d1 = TakeAWhile; d1.BeginInvoke(1, 3000, //lambda表达式 asyncResult => { int result = d1.EndInvoke(asyncResult); Console.WriteLine("result: {0}", result); }, d1); for(int i = 0; i < 15; i++) { //异步未完成,主线程执行 Console.WriteLine("."); Thread.Sleep(500); } Console.ReadKey(); } } }
结果:
2.需要先执行完主线程,再执行子线程
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Threading; namespace WpfBeginInvokeTest { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); this.Loaded += MainWindow_Loaded; } private void MainWindow_Loaded(object sender, RoutedEventArgs e) { //new Action(() => //{ // Console.WriteLine("new child thread and run child thread"); //} //).BeginInvoke(null, null); Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => { Console.WriteLine("new child thread and run main thread"); })); int i = 0; while (true) { i++; if (i > 100000000) break; } Console.WriteLine("not new child thread and run main thread"); //new Action(() => //{ // Console.WriteLine("not new child thread and run main thread"); //} //).Invoke(); //Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Background, new Action(() => //{ // Console.WriteLine("not new child thread and run main thread"); //})); } } }
结果:
注:要设置一下,即时窗口才可以显示