MethodInvoker和Invoker
2015-08-13 12:01
211 查看
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading; using System.Windows.Forms; namespace SQL_browser { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { /* * 1.MethodInvoke和Action都是方法返回类型为空的委托. * 2.MethodInvoker的原型定义为---> public delegate void MethodInvoker(); */ //Delegate d1 = (MethodInvoker)delegate { }; //Delegate d2 = (MethodInvoker)(() => { }); //Delegate d3 = (Action)delegate { }; //Delegate d4 = (Action)(() => { }); Thread t = new Thread(() => { Enumerable.Range(1, 10).ToList().ForEach(x => { if (listBox1.InvokeRequired) { listBox1.Invoke((Action)(() => { listBox1.Items.Add(string.Format("[{0}] executed 【 (Action)(() => {{ }}) 】", x)); })); } }); Enumerable.Range(11, 10).ToList().ForEach(x => { if (listBox1.InvokeRequired) { listBox1.Invoke((Action)delegate { listBox1.Items.Add(string.Format("[{0}] executed 【 (Action)delegate {{ }} 】", x)); }); } }); Enumerable.Range(21, 10).ToList().ForEach(x => { if (listBox1.InvokeRequired) { listBox1.CCInvoke(() => //使用lambda表达式 { listBox1.Items.Add(string.Format("[{0}] executed 【 lambda 】", x)); }); listBox1.CCInvoke(delegate //使用委托 { listBox1.Items.Add(string.Format("[{0}] executed 【 delegate 】", x)); }); } }); }); t.Start(); } } private void button2_Click(object sender, EventArgs e) { listBox1.Items.Clear(); Task taskWithFactoryAndState1 = Task.Factory.StartNew<List<int>>((stateObj) => { List<int> ints = new List<int>(); for (int i = 0; i < (int)stateObj; i++) { ints.Add(i); } return ints; }, 100).ContinueWith(ant => { listBox1.DataSource = ant.Result; }, TaskScheduler.FromCurrentSynchronizationContext()); } public static class ControlExtend { public static void CCInvoke(this Control control, Action action) { if (control.IsDisposed) return; try { control.Invoke((Delegate)action); } catch (ObjectDisposedException ode) { } catch (InvalidOperationException iox) { } } } } </int></int></int>
注意:button2_Click的方法会阻塞UI线程,如果数据量大或者里面的方法很耗时,界面会有卡死假象,比如窗体拖不动
相关文章推荐
- hdu 5095 Linearization of the kernel functions in SVM (简单模拟)
- NSDictionary、NSMutableDictionary的基本用法
- Linux基础系列(三)Linux系统文件和目录重要知识
- hdu1870愚人节的礼物之天呐你们为什么要骗我用栈才能过。。。大水题。。。
- 开发板sqlite数据库的搭建
- Win10 Mobile预览版10512:安卓子系统被严重破坏 键盘输入法无法弹出
- Java 删除文件或文件夹
- PHP 类中的静态变量的继承
- 面向对象和面向组件的区别
- SSH框架的应用介绍(spring、struts、hibernate) ---阿冬专栏
- android 应用自身检测版本并下载
- 如何停止处于stopping状态的windows服务
- WAP
- Thor:思科的开源免专利视频编解码器项目
- java.util.Date、java.sql.Date、java.sql.Time、java.sql.Timestamp区别和联系
- 优势与应用:再谈CDN镜像加速技术
- JSP页面间的参数传递
- Windows下编译 32位和64位 OpenSSL 2016-04-12
- 计算机超过远程连接数量,可以添加一个技巧
- Pywinauto在Windows Twain Driver自动化测试中的应用研究