Dưới đây là một số mảnh dễ dàng mã để hiển thị các hành vi bất ngờ:nhiệm vụ Nội được thực hiện trong một chủ đề bất ngờ
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
_UI = TaskScheduler.FromCurrentSynchronizationContext();
Loaded += new RoutedEventHandler(MainWindow_Loaded);
}
TaskScheduler _UI;
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
Task.Factory.StartNew(() =>
{
//Expected: Worker thread
//Found: Worker thread
DoSomething();
})
.ContinueWith(t =>
{
//Expected: Main thread
//Found: Main thread
DoSomething();
Task.Factory.StartNew(() =>
{
//Expected: Worker thread
//Found: Main thread!!!
DoSomething();
});
}, _UI);
}
void DoSomething()
{
Debug.WriteLine(Thread.CurrentThread.ManagedThreadId.ToString());
}
}
Tại sao nhiệm vụ bên trong thực hiện trong các chủ đề chính? Làm cách nào để ngăn chặn hành vi này?
Ah tuyệt vời, điều đó đã giúp tôi rất nhiều. Cảm ơn nhiều. –