我知道我错过了一些愚蠢的东西,“StartProcess”方法导致用户界面无响应,没有任何数量的谷歌搜索和教程让我得到答案。WPF异步任务锁定用户界面
这里是我的代码:
public MainWindow()
{
InitializeComponent();
txtBlock.Text = "Testing";
Initialize();
}
public void Initialize()
{
uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
StartProcess();
}
async void StartProcess()
{
Task<int> result = Task.Factory.StartNew(() =>
{
txtBlock.Text += ("\n starting updater");
while (true)
{
Thread.Sleep(3000);
}
return 0;
}, CancellationToken.None, TaskCreationOptions.LongRunning, uiScheduler);
}
一些背景:我建立有轮询DB每5分钟和一个待办事项列表供用户更新用户界面的应用程序,因此而(真)循环。应用程序必须在其整个生命周期内不断调查数据库。
你可以尝试使用'取代'Thread.Sleep' Task.Delay'。目前,您似乎在UI线程上调用了“Thread.Sleep”,这会使您的UI无响应。此外,简单地让你的方法'异步'不会执行魔术。 – 2014-09-10 15:17:20
你应该看看[Rx](http://stackoverflow.com/tags/system.reactive/info“system.reactive”)。 – 2014-09-10 16:08:00