我的代码如下
public CountryStandards()
{
InitializeComponent();
try
{
FillPageControls();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Country Standards", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
/// <summary>
/// Fills the page controls.
/// </summary>
private void FillPageControls()
{
popUpProgressBar.IsOpen = true;
lblProgress.Content = "Loading. Please wait...";
progress.IsIndeterminate = true;
worker = new BackgroundWorker();
worker.DoWork += new System.ComponentModel.DoWorkEventHandler(worker_DoWork);
worker.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(worker_ProgressChanged);
worker.WorkerReportsProgress = true;
worker.WorkerSupportsCancellation = true;
worker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
worker.RunWorkerAsync();
}
private void worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
GetGridData(null, 0); // filling grid …Run Code Online (Sandbox Code Playgroud) 我正在构建一个WPF应用程序.我正在与服务器端进行一些异步通信,我在客户端上使用Prism进行事件聚合.这两件事导致产生新的线程,而不是UI线程.如果我尝试在这些回调和事件处理程序线程上执行"WPF操作",那么世界将会崩溃,现在它已经开始了.
首先,我遇到了尝试在服务器回调中创建一些WPF对象的问题.我被告知线程需要在STA模式下运行.现在我正在尝试更新Prism事件处理程序中的一些UI数据,我被告知:
调用者无法访问此线程,因为另一个线程拥有它.
所以; 在WPF中解决问题的关键是什么?我在这篇MSDN帖子中读到了WPF Dispatcher .我开始明白了,但我还没有巫师.
有人想帮我清理一下吗?任何相关的建议等?谢谢!
我有一个通过插座连接的硬件,
现在我必须每隔5秒检查硬件是否已连接,复选框显示
我已经实现了一个功能:
private static System.Timers.Timer aTimer;
public MainWindow()
{
InitializeComponent();
client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), client);
aTimer = new System.Timers.Timer();
aTimer.AutoReset = true;
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Interval = 2000;
aTimer.Enabled = true;
}
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
if (client.Connected == true)
{
Console.WriteLine("Not Connected");
CheckBox.IsChecked = false;
}
else
{
Console.WriteLine("Connected");
CheckBox.IsChecked = false;
}
}
Run Code Online (Sandbox Code Playgroud)
但是当我运行应用程序时,它会抛出错误.
调用线程无法访问此对象,因为另一个线程拥有它.
我研究并了解了Dispatcher.Invoke但未能在我的代码中实现它.
我知道有类似的问题,比如Here And Here,我看了他们一切,但他们似乎不适合我.
我有一个帖子:
private void Sample()
{
Thread t = new Thread(new ThreadStart(Sample_Thread));
t.SetApartmentState(ApartmentState.STA);
t.Start();
}
Run Code Online (Sandbox Code Playgroud)
在Sample_Thread中,我之前调用过MessageBox哪个工作正常.
private void Sample_Thread()
{
try{ ... }
catch(Exception e)
{
MessageBox.Show("SampleText");
}
}
Run Code Online (Sandbox Code Playgroud)
现在我尝试调用ModernDialog而不是MessageBox,它给了我错误,'The calling thread cannot access this object because a different thread owns it.'
所以我将我的代码更改为:
private void Sample_Thread()
{
try{ ... }
catch(Exception e)
{
Dispatcher.CurrentDispatcher.Invoke(() =>
{
ModernDialog.ShowMessage("SampleText");
});
}
}
Run Code Online (Sandbox Code Playgroud)
但是这仍然有同样的错误,我应该如何解决这个问题呢?谢谢!