gpt4 book ai didi

c# - GUI 在 Dispatcher.BeginInvoke 或 Task.StartNew 时卡住

转载 作者:太空宇宙 更新时间:2023-11-03 22:00:07 25 4
gpt4 key购买 nike

注意:取决于 this quetion

我有一个像这样的 View 模型:

public class ViewModel {
private readonly IPersonService _personService;
private readonly ObservableCollection<SearchPersonModel> _foundedList;
private readonly DispatcherTimer _timer;
private readonly Dispatcher _dispatcher;
private CancellationTokenSource _tokenSource;

public SearchPatientViewModel(IPersonService personService) {
_personService = personService;
_foundedList = new ObservableCollection<SearchPersonModel>();
_dispatcher = (/*CurrentApplication*/).Dispatcher;
_timer = new DispatcherTimer(
TimeSpan.FromMilliseconds(1000),
DispatcherPriority.Normal,
TimerCallBack,
_dispatcher);
_tokenSource = new CancellationTokenSource();
}

public string Term {
get { return _term; }
set {
// implementing INotifyPropertyChanged
if(_term== value)
return;
_term= value;
OnPropertyChanged(() => Term);
tokenSource.Cancel(); // canceling prev search query
_timer.Stop(); // stop the timer to reset it
// start it again to do a search query if user change not the term for 1000ms
_timer.Start();
}
}

private void TimerCallBack(object sender, EventArgs e) {
_timer.Stop();
_tokenSource = new CancellationTokenSource();
var task = Task<IEnumerable<SearchPersonModel>>.Factory
.StartNew(Search, _tokenSource.Token);
_dispatcher.BeginInvoke((Action)(() => {
_foundedList.Clear();
foreach(var item in task.Result)
_foundedList.Add(item);
}), DispatcherPriority.Background);
}

private IEnumerable<SearchPersonModel> Search() {
return _personService.DoSearch(this.Term);
}

}

IPersonService 实现中,我这样做:

public class PersonService : IPersonService {
public IEnumerable<SearchPersonModel> DoSearch(string term){
System.Threading.Thread.Sleep(10000);
return some-search-result;
}
}

但是,我希望在执行搜索查询时,GUI 是免费的。但是它卡住了!你知道我的错误在哪里吗?

最佳答案

问题是评估 task.Result 将阻塞,直到查询完成。

最简单的选择可能是让 Search 方法在最后执行 _dispatcher.BeginInvoke 调用。

另一个选项(使用 C# 5 会变得更容易)是向任务添加延续,以便在任务完成时更新 UI。目前你会使用 Task.ContinueWith;对于 C# 5,您将使用 asyncawait

关于c# - GUI 在 Dispatcher.BeginInvoke 或 Task.StartNew 时卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10534290/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com