每当我刷新标签时,我都会收到此错误:调用线程无法访问此对象,因为另一个线程拥有它。我尝试调用但失败了。我正在使用 WPF 表单。
delegate void lostfocs(string st);
private void imgPayment_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Thread t = new Thread(modi);
t.Start();
}
void modi()
{
try
{
label1.Content = "df";
}
catch
{
lostfocs ld = new lostfocs(up);
// ld.Invoke("df");
object obj=new object();
ld.Invoke("sdaf");
}
}
void up(string st)
{
label1.Content = st;
}
使用Dispatcher.Invoke方法。
Executes the specified delegate synchronously on the thread the
Dispatcher is associated with.
还有
In WPF, only the thread that created a DispatcherObject may access
that object. For example, a background thread that is spun off from
the main UI thread cannot update the contents of a Button that was
created on the UI thread. In order for the background thread to
access the Content property of the Button, the background thread must
delegate the work to the Dispatcher associated with the UI thread.
This is accomplished by using either Invoke or BeginInvoke. Invoke is
synchronous and BeginInvoke is asynchronous. The operation is added to
the event queue of the Dispatcher at the specified DispatcherPriority.
您收到错误是因为您的标签是在 UI 线程上创建的,而您正试图通过另一个线程修改其内容。这是您需要 Dispatcher.Invoke 的地方。
看看这篇文章
WPF Threads Build More Responsive Apps With The Dispatcher