http://blog.csdn.net/xiaochongchong1248/archive/2009/11/20/4841193.aspx?1271573283

编程环境要求:VS2008/FX2.0

众所周知,从VS2005/FX2.0起,在多线程环境下是不允许跨线程修改主线程上窗口控件的。

例如:

private void button1_Click(object sender, EventArgs e)
{
    Thread t = new Thread(new ThreadStart(CrossThreadCall));
    t.Start();
}
public void CrossThreadCall()
{
    Text = "test";
}

将直接导致异常:
未处理 System.InvalidOperationException
  Message="线程间操作无效: 从不是创建控件“Form1”的线程访问它。"
  Source="System.Windows.Forms"
  StackTrace:
       在 System.Windows.Forms.Control.get_Handle()
       在 System.Windows.Forms.Control.set_WindowText(String value)
       在 System.Windows.Forms.Form.set_WindowText(String value)
       在 System.Windows.Forms.Control.set_Text(String value)
       在 System.Windows.Forms.Form.set_Text(String value)
       在 delegate_test1.Form1.CrossThreadCall() 位置 f:\app\delegate_test1\delegate_test1\Form1.cs:行号 26
       在 System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       在 System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       在 System.Threading.ThreadHelper.ThreadStart()

通用的解决方法是使用Control.Invoke方法来调用一个Delegate,从而安全地跨线程调用。

例如:

public void CrossThreadCall()
{
    Invoke(new void_d(CrossThreadCall_Local));
}
void CrossThreadCall_Local()
{
    Text = "test";
}
public delegate void void_d();

但是这样的缺点是要不得不为每个调用编写一个Invoke跳板,还要额外声明一个委托类型,实在不怎么优雅。

于是我们想到用匿名函数来写。我的第一反应是:

Invoke(delegate { Text = "test"; });

可惜不行。编译压根就没通过,写着:
无法将 匿名方法 转换为类型“System.Delegate”,因为它不是委托类型

无语,delegate竟然不是委托类型?

等我把Google翻了一遍后,找到了答案。

The problem the user is seeing is that the Thread ctor accepts a specific delegate -- the ThreadStart delegate.  The C# compiler will check and make sure your anonymous method matches the signature
of the ThreadStart delegate and, if so, produces the proper code under-the-covers to create the ThreadStart delegate for you.

But Control.Invoke is typed as accepting a "Delegate".  This means it can accept any delegate-derived type.  The example above shows an anonymous method that has a void return type and takes no parameters. 
It's possible to have a number of delegate-derived types that match that signature (such as MethodInvoker and ThreadStart -- just as an example).  Which specific delegate should the C# compiler use?  There's no way for it to infer the exact delegate type so
the compiler complains with an error.

也就是说,对于Thread.ctor()来说,由于接受的是一个ThreadStart委托,编译器便可以将匿名函数与ThreadStart委托类型匹配,最后能够正确编译。
而对于Control.Invoke()来说,任何的代理类型都是可接受的,也就是说ThreadStart和MethodInvoker都是可以接受的类型。这样编译器反而不知道应该用哪个代理去匹配匿名函数了,导致了编译错误的发生。

知道了原因,问题就很容易解决了。我们只需要加上MethodInvoker这个wrapper就能使用匿名函数了。

Invoke(new MethodInvoker(delegate { Text = "test"; }));

或者更简单地,用Lambda表达式来解决问题:

Invoke(new MethodInvoker(() => Text = "test"));

希望本文能够帮助有同样困惑的朋友。

作者: 火地晋 
出处: http://yelaiju.cnblogs.com 
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

无法将 匿名方法 转换为类型“System.Delegate”,因为它不是委托类型:解决方法的更多相关文章

  1. 关于委托:异常{ 无法将 匿名方法 转换为类型“System.Delegate”,因为它不是委托类型 }

    转自:http://www.cnblogs.com/xiaofei59/archive/2010/11/25/1887285.html 异常{ 无法将 匿名方法 转换为类型“System.Delega ...

  2. 关于委托:异常{ 无法将 匿名方法 转换为类型“System.Delegate”,因为它不是委托类型 }

    异常{ 无法将 匿名方法 转换为类型"System.Delegate",因为它不是委托类型 } 委托实际上是把方法名作为参数,但是若有好多个方法时,就要指明是哪个参数  查看如下代 ...

  3. 无法将 lambda 表达式 转换为类型“System.Delegate”,因为它不是委托类型

    今天写winform的时候遇到一个问题,提示: 无法将 lambda 表达式 转换为类型“System.Delegate”,因为它不是委托类型, 主要是为了在子线程中更新UI线程,在wpf中同样的写法 ...

  4. 无法读取配置节 system.serviceModel 因为它缺少节声明的解决方法

    无法读取配置节 system.serviceModel 因为它缺少节声明的解决方法,需要的朋友可以参考下 在Windows Server2008 R2中的IIS7中部署WCF服务时报出如题错误: HT ...

  5. MaterialDesignInXamlToolkit“无法绑定到目标方法,因其签名或安全透明度与委托类型的签名或安全透明度不兼容”异常的解决思路

    前言: 最初是想解答园友"小代码大世界 "的问题,后来想举一反三,将这个问题简单剖析下,做到知其所以然. MaterialDesignInXAML 控件库高度封装,有一些控件在使用 ...

  6. System.Data.OleDb.OleDbException: 未指定的错误的解决方法

    异常详细信息: System.Data.OleDb.OleDbException: 未指定的错误 这个错误是access数据库特有的错误,当access频繁读取或操作过多的时候就会发生这个错误,微软官 ...

  7. "System.Security.Cryptography.CryptographicException: 拒绝访问" 问题的解决方法

    .net web程序使用rsa算法进行加解密时,程序报告“System.Security.Cryptography.CryptographicException: 拒绝访问”错.按网上搜的解决方法做了 ...

  8. 异常详细信息: System.Web.Hosting.HostingEnvironmentException: 访问 IIS 元数据库失败 解决方法

    访问IIS元数据库失败 同理,给操作系统的新建用户赋予IIS操作权限同样可以采用该命令来处理 说明: 执行当前 Web 请求期间,出现未处理的异常.请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错 ...

  9. “System.Runtime.InteropServices.COMException (0x80070422): 无法启动服务”解决方法

    应用程序中发生了无法处理的异常.如果单击“退出”,应用程序将立即关闭.无法启动服务,原因可能是已被禁用或其相关联设备没有启动.(异常来自HRESULT:0X80070422).点击详细内容:有关调用实 ...

随机推荐

  1. URL tailing slash

    Without tailing slash request header GET /snippets HTTP/1.1 User-Agent: Fiddler Host: 192.168.128.13 ...

  2. PHP&MySQL(二)——困也得啃书

    madan,所有事情都敢赶在一起...以后每天中午去学车啊,好开心..晚上好困,但是困也得啃书........ 二.PHP脚本编程语言 什么变量啊,数据类型啊,特别特别基本的不记录了,说点容易忽略的. ...

  3. 2016-2017 ACM-ICPC, NEERC, Southern Subregional Contest (Online Mirror, ACM-ICPC Rules, Teams Preferred)

    A 思路: 贪心,每次要么选两个最大的,要么选三个,因为一个数(除了1)都可以拆成2和3相加,直到所有的数都相同就停止,这时就可以得到答案了; C: 二分+bfs,二分答案,然后bfs找出距离小于等于 ...

  4. using关键字的使用

    using语句的两个作用: 1)using可以导入命名空间 2)using可以释放对象占用的内存资源. 代码如下: using (SqlConnection con=new SqlConnection ...

  5. JAVA单例

    单例模式: 1 public class Person{ 2 public static Person per//定义一个静态变量,用来储存当前类的对象 3 private Person()//构造方 ...

  6. ArrayList的线程安全测试

    public class TestThread implements Runnable{ private List list; CountDownLatch cdl; public TestThrea ...

  7. AnjularJs的增删改查(单页网站)

    2016.6.4 学习文献: 你的第一个AngularJS应用:https://segmentfault.com/a/1190000000347412 AngularJS 提交表单的方式:http:/ ...

  8. C#的一维数组和二维数组定义方式:

    一维数组: //一维数组定义与初始化 ,, };//第一种方式 , , }; //第二种方式 int[] one3; //第三种方式 one3=,,}; 二维数组: //二维数组定义与初始化 //不规 ...

  9. 改变input默认选中颜色

    修改 outline-color 属性即可实现

  10. php正则表达式治疗结巴

    用正则表达式去解决结巴这个问题可以通过下面进行解决: 解决思路是: 先找到重复的不部分 用str_replace($source,$replace,$str);来进行代理 下面分两种情况,最后将这两种 ...