I'm stuck with await. I want my task to report some progress to gui with fashion way - ContinueWith and FromCurrentSynchronizationContext.
But GUI is blocked and does not refresh untill all tasks are completed. How do I fix this problem?
I think the reason is because tasks are running in the same pool and refresh gui tasks are added to the end of the queue. But, I don't know how to do it properly due to lack of experience
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Linq;
using System.Linq.Expressions;
namespace AsyncCallbackSample
{
public partial class MainForm : Form
{
private readonly Random _random = new Random();
public MainForm()
{
InitializeComponent();
}
private async void OnGoButtonClick(object sender, EventArgs e)
{
var uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
await Task.WhenAll(_listBox.Items
.OfType<string>()
.Select(
taskArgument =>
Task
.FromResult(DoLongTermApplication(taskArgument))
.ContinueWith(previousTask => _listBox.Items[_listBox.Items.IndexOf(taskArgument)] = previousTask.Result, uiScheduler) // refreshing the gui part while all other staff is in progress.
)
.ToArray());
}
private string DoLongTermApplication(string taskInformation)
{
Thread.Sleep(1000 + _random.Next(1000));
return $"Processed {taskInformation}";
}
}
}