我有很长的搜索操作,它会定期更新 UI(发现出现 -> 更新 UI)
我试图以多种方式实现它:
异步/等待
public void PushButton() { await AsyncSearchAll(); } public async Task AsyncSearchAll(SearchPanelViewModel searchPanelViewModel, SearchSettings searchSettings, CancellationToken cancellationToken) { await Task.Factory.StartNew(() => { //searching for occurence //write it into panel }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()); }
后台工作者
我想使用它,但我不想只使用 .ReportProgress() 访问 UI
带调用的简单后台线程
Dispatcher.BeginInvoke(()=>{//updating UI})
/// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow { public MainWindow() { InitializeComponent(); } private void ButtonBase_OnClick(object sender, RoutedEventArgs e) { var backgroundThread = new Thread(CountToTen) { IsBackground = true }; backgroundThread.Start(); } private void CountToTen() { for (int i = 1; i <= 10000; i++) { var j = i; Dispatcher.BeginInvoke(new Action(() => Seconds.Text = j.ToString(CultureInfo.InvariantCulture))); } }
完成线程后写入所有数据的所有方法。有没有什么方法可以运行后台任务,定期更新 UI 而不会通过阻止 ui 来减慢程序?