Dispatcher.Invoke与匿名委托工作在Silverlight但不是WPF [英] Dispatcher.Invoke with anonymous delegate works in Silverlight but not WPF
问题描述
在Silverlight 4中我有已经完成的事件的异步定制服务类。 Completed事件里面我把返回的数据,并通过像这样调用一个方法填充:
In Silverlight 4 I have a custom service class which has an asynchronous Completed event. Inside the Completed event I take the returned data and invoke a populate method via something like this:
private void service_Completed(object sender, CompletedEventArgs args)
{
Dispatcher.BeginInvoke(() => populateInbox(args.Jobs));
}
private void populateInbox(List<JobViewModel> jobs)
{
inbox.DataContext = jobs;
}
的的BeginInvoke在SL4然而,当我把它移植到WPF我收到以下错误
的作品,
无法转换拉姆达前pression键入'System.Delegate',因为它不是一个委托类型
Cannot convert lambda expression to type 'System.Delegate' because it is not a delegate type
我试图将其更改为直列,匿名paramaterized委托:
I tried changing it to an in-line, anonymous, paramaterized delegate:
Dispatcher.BeginInvoke(delegate(List<JobViewModel> jobs)
{
inbox.DataContext = jobs;
});
然而,能产生相同的编译时错误。
However, that yields the same compile-time error.
任何想法如何得到这个在WPF中工作?重构使用的BackgroundWorker
不是我的选择。
Any idea how to get this to work in WPF? Refactoring to use the BackgroundWorker
is not an option for me.
推荐答案
您需要指定一个明确的委托类型。只需使用动作
。
You need to specify an explicit delegate type. Just use an Action
.
Dispatcher.BeginInvoke(new Action(() => populateInbox(args.Jobs));
您可以,但是,避免关闭在 args.Jobs
值是这样的:
You could, however, avoid having to close over the args.Jobs
value like this:
Dispatcher.BeginInvoke(new Action((jobs) => populateInbox(jobs)), jobs);
这是因为 Dispatcher.BeginInvoke
的单参数版本的Silverlight中比在WPF不同的签名。在Silverlight中,它需要一个动作
,这使得C#编译器隐式键入您的拉姆达为动作
。在WPF中,它需要一个代表
(如Winforms中的 Control.BeginInvoke
模拟),所以C#编译器必须已委托类型明确指定。
This is because the single-parameter version of Dispatcher.BeginInvoke
has a different signature in Silverlight than in WPF. In Silverlight, it takes an Action
, which allows the C# compiler to implicitly type your lambda as an Action
. In WPF, it takes a Delegate
(like its Control.BeginInvoke
analog in Winforms), so the C# compiler has to have a delegate type explicitly specified.
这篇关于Dispatcher.Invoke与匿名委托工作在Silverlight但不是WPF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!