I have long search operations which periodically updates UI (found occurence -> Update UI)
I've tried to realize it many ways:
async/await
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());
}
BackgroundWorker
I want to use it but I don't want access UI using only .ReportProgress()
Simple background thread with calling 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)));
}
}
All methods writing all data after completing thread. Is there any method to run background task which periodically updating UI without slowing program by blocking ui?
It's best if you can separate your "worker" logic from your "UI update" logic.
Something like this:
public async Task AsyncSearchAll(SearchPanelViewModel searchPanelViewModel, SearchSettings searchSettings, CancellationToken cancellationToken)
{
while (..)
{
var results = await Task.Run(() => /* search more */);
/* update panel with results */
}
}
But if you want actual progress updates, there's ways to do that too:
public async void PushButton()
{
Progress<MyUpdateType> progress = new Progress<MyUpdateType>(update =>
{
/* update panel */
});
await Task.Run(() => SearchAll(..., progress));
}
public void SearchAll(SearchPanelViewModel searchPanelViewModel,
SearchSettings searchSettings, CancellationToken cancellationToken,
IProgress<MyUpdateType> progress)
{
while (..)
{
/* search more */
if (progress != null)
progress.Report(new MyUpdateType(...));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With