我阅读了有关BackgroundWorker类的this guide。
我正在尝试实现重置按钮,因此我添加了以下代码。
在 Page.xaml :
中<Button x:Name="buttonReset" Content="Reset" Click="buttonReset_Click"
Width="80" Height="30"/>
并在 Page.cs :
中 private void buttonReset_Click(object sender, RoutedEventArgs e)
{
if (bw.WorkerSupportsCancellation == true)
{
bw.CancelAsync();
}
// How to restart?
bw.RunWorkerAsync(); // Raises busy exception
}
但我得到以下错误:
来自意大利语:
此BackgroundWorker正忙,无法同时执行多个任务
仅当我按开始 a 然后 重置时才会发生这种情况。
为什么呢?以及如何解决?
答案 0 :(得分:-1)
请注意,即使有效
,这也是一个糟糕的解决方案
我试过了:
private void buttonReset_Click(object sender, RoutedEventArgs e)
{
if (bw.WorkerSupportsCancellation == true)
{
bw.CancelAsync();
while (bw.IsBusy)
{
DoEvents();
}
}
bw.RunWorkerAsync();
}
public static void DoEvents()
{
Application.Current.Dispatcher.Invoke(DispatcherPriority.Background,
new Action(delegate { }));
}
这解决了这个问题。
特别是我补充道:
while (bw.IsBusy)
{
DoEvents();
}
其中定义了DoEvents()
:
public static void DoEvents()
{
Application.Current.Dispatcher.Invoke(DispatcherPriority.Background,
new Action(delegate { }));
}
如上所述(here)。
注意:特别感谢一位神秘的用户在这里回复但删除了他的答案。