Sum*_*Guy 3 c# wpf events asynchronous event-handling
我正在尝试创建一个与主进程异步工作的进度条.我创建了一个新事件并调用它然后每次我尝试在进度条上执行操作时我收到以下错误:
"调用线程无法访问此对象,因为另一个线程拥有它"
以下代码是尝试将进度条的实例作为对象发送到事件,它显然失败了,但它让您了解代码的外观.
private event EventHandler importing;
void MdbDataImport_importing(object sender, EventArgs e)
{
ProgressBar pb = (ProgressBar)sender;
while (true)
{
if (pb.Value >= 200)
pb.Value = 0;
pb.Value += 10;
}
}
private void btnImport_Click(object sender, RoutedEventArgs e)
{
importing += new EventHandler(MdbDataImport_importing);
IAsyncResult aResult = null;
aResult = importing.BeginInvoke(pbDataImport, null, null, null);
importing.EndInvoke(aResult);
}
Run Code Online (Sandbox Code Playgroud)
有没有人有如何做到这一点的想法.
在此先感谢SumGuy.
你应该使用这样的东西
pb.Dispatcher.Invoke(
System.Windows.Threading.DispatcherPriority.Normal,
new Action(
delegate()
{
if (pb.Value >= 200)
pb.Value = 0;
pb.Value += 10;
}
));
Run Code Online (Sandbox Code Playgroud)
在你的while循环中