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"); //})); } } }
结果:
注:要设置一下,即时窗口才可以显示
分类:
C#
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义