我的代码是
Ping ping = new Ping(); ping.PingCompleted += ping_PingCompleted; ping.SendAsync(strTerminalName, 60, Encoding.ASCII.GetBytes("sfk")); private void ping_PingCompleted(object sender, PingCompletedEventArgs e) { Terminal.ChangeTerminalStatus(this.imgCurrent, TerminalStatus.UserOFF); }
终端具有静态方法ChangeTerminalStatus,我正在ping_PingCompleted中调用它。
错误我得到了:-
The calling thread cannot access this object because a different thread owns it WPF.
由于我试图在该statis方法中更改窗口的UI属性。
我搜索并找到了使用Dispatcher.BeginInvoke方法的解决方案 。
当我尝试在具有ping,Dispatcher.BeginInvoke的类中使用它时,抛出错误提示
Error 2 An object reference is required for the non-static field, method, or property 'System.Windows.Threading.Dispatcher.BeginInvoke(System.Delegate, params object[])' D:\Net Projects\mercurial\icafemanager\ICMBusiness\Terminal.cs 124 17 ICM
帮我解决这个问题。
BeginInvoke不是Dispatcher类的静态方法。您需要一个调度程序实例来调用它。在您的教程中,您从中调用的类可能有一个名为dispatcher的成员,因此可以将其称为
this.Dispatcher.BeginInvoke(...);
如果需要当前的Dispatcher,则可以使用静态属性CurrentDispatcher来获取它:
Dispatcher.CurrentDispatcher.BeginInvoke(...);
如果您的类已经有一个调度程序对象,则使用它可能更快。