Silverlight与WPF中BeginInvoke的差异

Silverlight/WPF中,如果要在多线程中对界面控件值做修改,用Dispatcher对象的BeginInvoke方法无疑是最方便的办法


silverlight中的代码片段:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
private  void  button1_Click( object  sender, RoutedEventArgs e)
{
     Thread t = new  Thread(TestMethod);           
     t.Start();
 
     Thread t2 = new  Thread(TestMethod2);
     t2.Start( "Hello World" );
}
 
void  TestMethod() {
     this .Dispatcher.BeginInvoke(() => { this .textBlock1.Text = DateTime.Now.ToString( "HH:mm:ss" ); });           
}
 
void  TestMethod2( object  s)
{
     this .Dispatcher.BeginInvoke(() => { this .textBlock1.Text =s.ToString() ; });
}

WPF中如果这样用,会报如下错误: 

Cannot convert lambda expression to type 'System.Delegate' because it is not a delegate type

即:无法将lambda表达式转换为"System.Delegate",因为它不是delegate 类型


即使把Lambda表达式改成匿名方法的写法也不行:

?
1
2
3
4
public  void  TestMethod()
{
     this .Dispatcher.BeginInvoke( delegate () { this .textBlock1.Text = DateTime.Now.ToString( "HH:mm:ss fff" ); });
}

仍然会报错:
Cannot convert anonymous method to type 'System.Delegate' because it is not a delegate type

即:无法将匿名方法转换为"System.Delegate",因为它不是delegate 类型


当然也可以自己定义一个Delegate类型用最传统的方法来写:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
delegate  void  MyDelegate();
delegate  void  MyDelegate2( object  s);
 
 
 
public  void  TestMethod()
{
     MyDelegate d = new  MyDelegate(UpdateText);
     this .Dispatcher.BeginInvoke(d);
}
 
void  UpdateText()
{
     this .textBlock1.Text = DateTime.Now.ToString( "HH:mm:ss fff" );
}
 
void  UpdateText2( object  s)
{
     this .textBlock1.Text = s.ToString();
}
 
public  void  TestMethod2( object  s)
{
     MyDelegate2 d = new  MyDelegate2(UpdateText2);
     this .Dispatcher.BeginInvoke(d, "Hello World" );
}

但是这种写法太繁琐了,还得单独把方法的定义提取出来,同时还要定义相应的委托类型,难道不能象Silverlght中那样清爽一点么?

既然出错的原因就是编译器不自动做类型转换,那我们就来强制转换吧

?
1
2
3
4
5
6
7
8
9
public  void  TestMethod()
{
     this .Dispatcher.BeginInvoke((Action) delegate () { this .textBlock1.Text = DateTime.Now.ToString( "HH:mm:ss fff" ); });
}       
 
public  void  TestMethod2( object  s)
{
     this .Dispatcher.BeginInvoke((Action)(() => { this .textBlock1.Text = s.ToString(); }));
}

 

这样就可以了,把匿名方法/Lambda表达式强制转换为Action,而Action实质就是委托类型,so,问题解决了!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值