私は間違っているかもしれませんが、特定の順序を気にしなければ、バックグラウンドスレッドはListまたはObservableCollectionに読み書きできます。余分な注文が必要な場合は、BlockingCollectionを使用します。タスクの実行中にUIがフリーズする
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();
}
(注:私はそれが重要なのかどうかわからないです - 「ペア」が反射によって発見された) 私は最後の行を聞くことができ、ボタンをクリックしてください - System.Media.SystemSounds.Beep.Play() ;イベントハンドラからすべてのスレッドが起動されることを意味します。しかし、その後、私のアプリケーションは、ContinueWhenAllが完了するまで、まだフリーズしています。 TestPairSerial(ペア)メソッドは、以下の構造を有する:
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)
}
残りの方法は表示できますか?また、UIがフリーズしたときに実行を一時停止し、mainthreadが停止している場所を確認することもできます。 –
私は中断しようとしましたが、それは複数のメソッドの中にあります(TestPairSerial内)。申し訳ありませんが、表示するにはあまりにも多くのコードがあります(私はエッセンスを表示するために最善を尽くしました)。 – Vitaly
私はMSDNフォーラムで同じ質問をしようとしました。彼らの答えが理にかなっているように見えます。 http://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/74b2c600-83ad-4890-b2b2-27d8f07f5a90 – Vitaly