C# BeginInvoke用法记录
一、简述
简单记录一下C# BeginInvoke(异步委托)涉及的知识点,以便随时可查询。
二、内容
BeginInvoke有以下几种用法:
private void lblContentText(string val) { if (lblContent.InvokeRequired) { lblContent.Invoke(new Action<string>(lblContentText), new object[] { val }); } else { lblContent.Text += val; } } public string TestFunction(int ms) { string content = "执行结果;"; Thread.Sleep(ms); return content; } private void Main() { Thread thread = new Thread(() => { Func<int, string> action = TestFunction; //lblContentText(action.Invoke(3000)); //界面一起输出“执行结果;abc;” //IAsyncResult iasr = action.BeginInvoke(3000, (val) => //{ // lblContentText(action.EndInvoke(val)); //}, null); //界面先输出“abc;”,再输出“执行结果” IAsyncResult iasr = action.BeginInvoke(3000, null, null); int i = 0; while (!iasr.AsyncWaitHandle.WaitOne(200/*每200毫秒检测一次*/)) { lblRemarkText((++i).ToString()); } lblContentText(action.EndInvoke(iasr)); //先进行计数,然后一起输出“执行结果;abc;” lblContentText("abc;"); }); thread.IsBackground = true; thread.Start(); }
BeginInvoke 是在Thread里面执行的,主要是防止UI界面假死。