我正在尝试在线程在后台工作时为加载屏幕设置动画,但它不起作用。
我意识到它与调用 Button.Dispatcher 的后台工作人员有关,但是我无法删除它,因为它会导致线程错误。我应该怎么做才能解决这个问题?
下面是我的代码:
private void btnLogin_Click(object sender, RoutedEventArgs e)
{
Storyboard sb = (Storyboard)FindResource("Loading");
sb.Dispatcher.BeginInvoke(new Action(() => sb.Begin()), DispatcherPriority.Normal, null);
BackgroundWorker bg = new BackgroundWorker();
bg.DoWork += new DoWorkEventHandler(bg_DoWork);
bg.RunWorkerAsync();
}
private void bg_DoWork(object sender, DoWorkEventArgs e)
{
System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(RunThread));
thread.Start();
}
private void RunThread()
{
btnLogin.Dispatcher.BeginInvoke(new Action(() => TheBackgroundWork()), DispatcherPriority.Normal, null);
}
更新:
按照 Jay 的建议,我从 Do_Worker 中删除了 UI 调用。不幸的是,我仍然遇到错误:
The calling thread cannot access this object because a different thread owns it.
它是由我的网络服务客户端抛出的
以下是更新后的代码:
private WebServiceClient proxy = new WebServiceClient();
private void btnLogin_Click(object sender, RoutedEventArgs e)
{
sb = (Storyboard)FindResource("sbLoading");
sb.Dispatcher.BeginInvoke(new Action(() => sb.Begin()), DispatcherPriority.Normal, null);
BackgroundWorker bg = new BackgroundWorker();
bg.DoWork += new DoWorkEventHandler(bg_DoWork);
bg.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bg_RunWorkerCompleted);
bg.RunWorkerAsync();
}
private void bg_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
var u = e.Result;
if (u != null)
//pass the data
}
private void bg_DoWork(object sender, DoWorkEventArgs e)
{
try
{
var u = proxy.ToWebService(x,y); //this guy throws an error
e.Result = u;
}
catch
{
this.Dispatcher.Invoke(new Action(
() => MessageBox.Show("Connection Error", this.Title)),
DispatcherPriority.Normal, null);
}
}