我必须在UI线程中做一些事情。因此,我这样做:
Dispatcher.Invoke(() =>{ what I must do in the UI thread}
当我将此行放在函数中时,它可以工作,但在本示例中的委托中却不起作用:
public Action f = () => // it does'nt work
{
Dispatcher.Invoke(() => {what I must do in the UI thread });
}
public void ff() // it works
{
Dispatcher.Invoke(() => { what I must do in the UI thread });
}
错误如下:
字段初始化器不能引用非静态字段,方法或属性DispatcherObjet.Dispatcher
答案 0 :(得分:2)
您不能在初始化程序中引用this.Dispatcher
。
以下内容应该起作用,或者至少将错误移至在UI线程中必须执行的操作
public Action f = () => // it should work
{
Application.Current.Dispatcher.Invoke(() => {what I must do in the UI thread });
}
答案 1 :(得分:0)
您需要在构造函数中初始化字段f
:
public class YourClassName
{
public Action f;
public YourClassName()
{
f = () =>
{
Dispatcher.Invoke(() => {what I must do in the UI thread });
}
}
}
这是怎么回事,f
是您班上的一个领域。像您使用的那样的字段初始化器无权访问该类的实例成员,而只能访问静态成员。
如果需要访问实例成员,则需要在实例成员(如构造函数)中初始化字段。