在运行Task时,UI被冻结
本文关键字:UI 冻结 运行 Task | 更新日期: 2023-09-27 18:18:57
可能是我错了,但我的假设是,任何后台线程可以读写到列表或ObservableCollection,如果我不关心任何特定的顺序。如果我需要一个特定的订单,我将使用BlockingCollection。
private void buttonTesting_Click(object sender, RoutedEventArgs e)
{
PrepareDataForTesting();
Stopwatch timer1 = new Stopwatch();
timer1.Start();
//some code preparing data
List<Task> tasks = new List<Task>();
//Testing for each pair
foreach (InterfaceWithClassName aCompound in Group1)
{
foreach (InterfaceWithClassName bCompound in Group2)
{
InstancePair pair = new InstancePair();
//some code
Task task = Task.Factory.StartNew(() => TestPairSerial(pair));
tasks.Add(task);
}
}
var ui = TaskScheduler.FromCurrentSynchronizationContext();
Task.Factory.ContinueWhenAll(tasks.ToArray(),
antecedents =>
{
timer1.Stop();
TimeSpan ts1 = timer1.Elapsed;
string elapsedTime1 = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts1.Hours, ts1.Minutes, ts1.Seconds, ts1.Milliseconds / 10);
statusLabel_1.Content = "Elapsed time to run the test" + elapsedTime1;
statusLabel_0.Content = "Testing made " + passes + " passes";
pairsResultsDataGrid.ItemsSource = pairsResultsTable.DefaultView;
System.Media.SystemSounds.Exclamation.Play();
}, CancellationToken.None, TaskContinuationOptions.None, ui);
System.Media.SystemSounds.Beep.Play();
}
(注意:我不确定它是否重要-"pair"是通过反射找到的)当我点击按钮时,我可以听到最后一行- System.Media.SystemSounds.Beep.Play();这意味着我们退出事件处理程序并启动所有线程。但是,我的应用程序仍然冻结,直到ContinueWhenAll完成。TestPairSerial(pair)方法的结构如下:
private void TestPairSerial(object instances)
{
do
{
do
{
//here are two methods that read data from minData ObservableCollection
//minData is a public static property of MainWindow
//minData is bound to Chart control (in XAML)
} while (isSetbCompoundParams);
} while (isSetaCompoundParams);
//filling up results into one table and two dictionaries (main window variables)
}
您正在主线程中执行任务。您可以使用Dispatcher.BeginInvoke
this.Dispatcher.BeginInvoke(new Action(() => {
// your code here
}), null);