GUI is freezed till all tasks are finished - c#

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}";
}
}
}

You should follow these guidelines:
Don't use ContinueWith, ever. Use await instead.
Don't use TaskSchedulers, unless you absolutely have to. Use await instead.
Use Task.Run to run synchronous code on a thread pool thread. Task.FromResult is not appropriate for this.
Combining these:
private async void OnGoButtonClick(object sender, EventArgs e)
{
await Task.WhenAll(_listBox.Items.OfType<string>()
.Select(taskArgument => ProcessAsync(taskArgument)));
}
private async Task ProcessAsync(string taskArgument)
{
var result = await Task.Run(() => DoLongTermApplication(taskArgument));
_listBox.Items[_listBox.Items.IndexOf(taskArgument)] = result;
}
private string DoLongTermApplication(string taskInformation)
{
Thread.Sleep(1000 + _random.Next(1000));
return $"Processed {taskInformation}";
}
Alternatively, if your DoLongTermApplication can be made truly asynchronous (e.g., by replacing Thread.Sleep with Task.Delay), then you don't need Task.Run either:
private async void OnGoButtonClick(object sender, EventArgs e)
{
await Task.WhenAll(_listBox.Items.OfType<string>()
.Select(taskArgument => ProcessAsync(taskArgument)));
}
private async Task ProcessAsync(string taskArgument)
{
var result = await DoLongTermApplicationAsync(taskArgument);
_listBox.Items[_listBox.Items.IndexOf(taskArgument)] = result;
}
private async Task<string> DoLongTermApplicationAsync(string taskInformation)
{
await Task.Delay(1000 + _random.Next(1000)).ConfigureAwait(false);
return $"Processed {taskInformation}";
}
Since you're new to async, I recommend reading my async intro blog post and following up with my MSDN article on async best practices.

Use Thread.Sleep when you want to block current (UI in your case) thread.
See: When to use Task.Delay, when to use Thread.Sleep?
Try something along these lines:
private async void OnGoButtonClick(object sender, EventArgs e)
{
var uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
await Task.WhenAll(_listBox.Items
.OfType<string>()
.Select(
taskArgument =>
Task.Run(async () => await DoLongTermApplicationAsync(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 async Task<string> DoLongTermApplicationAsync(string taskInformation)
{
await Task.Delay(1000 + _random.Next(1000));
return $"Processed {taskInformation}";
}

Related

c# async await and exception

I wrote a visual studio 2015 c# program for reading from a custom Ethernet device some data. I need to use async await instructions because the data will be read all together on scheduled times.
I use a custom .NET library for read data; this is my code:
private void timerPollingData_Tick(object sender, EventArgs e)
{
readDevice_01();
readDevice_02();
// and so on for all devices ...
}
private async void readDevice_01()
{
var result = await getDataDevice_01();
// Save data
}
private async void readDevice_02()
{
var result = await getDataDevice_02();
// Save data
}
private Task<string> getDataDevice_01()
{
MyCustomLibrary readDevice = new MyCustomLibrary.Master();
return Task.Factory.StartNew(() => readDevice.ReadHoldingRegister(... some parameters ...).ToString());
}
private Task<string> getDataDevice_02()
{
MyCustomLibrary readDevice = new MyCustomLibrary.Master();
return Task.Factory.StartNew(() => readDevice.ReadHoldingRegister(... some parameters ...).ToString());
}
My doubt:
what is the best practice for handle exception of each Task? I need to understand what devices are unplug from Ethernet or switch off and then STOP the TASK used to retrieve data from it.
Thanks a lot in advance for your help.
You should avoid async void; use async Task for everything except async event handlers. For more information, see my article on async best practices.
Also, you should not use StartNew; it's a low-level, very dangerous API with inappropriate default parameter values. Use Task.Run instead of StartNew. For more information, see my blog post on StartNew is dangerous.
I need to use async await instructions because the data will be read all together on scheduled times.
Asynchrony is one form of concurrency, which you can use with Task.Run if your device API does not have asynchronous methods:
private async void timerPollingData_Tick(object sender, EventArgs e)
{
var task1 = readDevice_01();
var task2 = readDevice_02();
// and so on for all devices ...
await Task.WhenAll(task1, task2, ...);
}
private async Task readDevice_01()
{
var result = await Task.Run(() => getDataDevice_01());
// Save data
}
private string getDataDevice_01()
{
MyCustomLibrary readDevice = new MyCustomLibrary.Master();
return readDevice.ReadHoldingRegister(... some parameters ...).ToString();
}
If your API had a ReadHoldingRegisterAsync method, then this would be more naturally expressed as:
private async void timerPollingData_Tick(object sender, EventArgs e)
{
var task1 = readDevice_01Async();
var task2 = readDevice_02Async();
// and so on for all devices ...
await Task.WhenAll(task1, task2, ...);
}
private async Task readDevice_01Async()
{
var result = await getDataDevice_01Async();
// Save data
}
private async Task<string> getDataDevice_01Async()
{
MyCustomLibrary readDevice = new MyCustomLibrary.Master();
var result = await readDevice.ReadHoldingRegisterAsync(... some parameters ...);
return result.ToString();
}
My doubt: what is the best practice for handle exception of each Task? I need to understand what devices are unplug from Ethernet or switch off and then STOP the TASK used to retrieve data from it.
The best practices for getting exceptions from tasks are to await them.
You don't have to worry about stopping a task after it raised an exception. By the time the task reports its exception, it has already stopped.

Monitoring Task completion

I run several tasks and keep them in a list to check if they are already completed.
I discovered that tasks that come from an async method are always shown as RanToCompletion although the task itself was still running.
Is there a way to get the "is complete" information from a Task object in both cases?
Here's a simple test case that shows this behaviour. I run two tasks, with/without an async method and check the states during and after completion.
private void test()
{
;
Action actionAsync = funcAsync;
Task taskAsync = Task.Run(actionAsync);
Action action = func;
Task task = Task.Run(action);
var statusAsync = taskAsync.Status;
var status = task.Status;
// stati are either WaitingToRun or Running
Thread.Sleep(TimeSpan.FromSeconds(2));
// Now it's quite certain, that both have started
var statusAsync2 = taskAsync.Status;
var status2 = task.Status;
Debug.Assert(statusAsync2 == TaskStatus.RanToCompletion);
Debug.Assert(status2 == TaskStatus.Running);
;
Thread.Sleep(TimeSpan.FromSeconds(12));
// Now it's quite certain, that both have finished
var statusAsync3 = taskAsync.Status;
var status3 = task.Status;
;
Debug.Assert(statusAsync3 == TaskStatus.RanToCompletion);
Debug.Assert(status3 == TaskStatus.RanToCompletion);
}
private async void funcAsync()
{
await Task.Delay(TimeSpan.FromSeconds(10));
}
private void func()
{
Thread.Sleep(TimeSpan.FromSeconds(10));
}
I discovered that tasks that come from an async method are always shown as RanToCompletion although the task itself was still running.
Yes, because your void method has completed, and that's all that Task.Run is calling. If instead you use:
private async Task FuncAsync()
{
await Task.Delay(TimeSpan.FromSeconds(10));
}
and use Func<Task> instead Action, then you'll call Task.Run(Func<Task>) and all will be well.
Short but complete example:
using System;
using System.Threading;
using System.Threading.Tasks;
class Test
{
static void Main()
{
Func<Task> func = FuncAsync;
Task task = Task.Run(func);
for (int i = 0; i < 7; i++)
{
Console.WriteLine(task.Status);
Thread.Sleep(1000);
}
}
private static async Task FuncAsync()
{
await Task.Delay(TimeSpan.FromSeconds(5));
}
}
Output:
WaitingForActivation
WaitingForActivation
WaitingForActivation
WaitingForActivation
WaitingForActivation
RanToCompletion
RanToCompletion
Try to avoid writing void async methods if you possibly can. They should basically only be used for event handlers.

Take the Last Requested Async Result and Cancelling Previous Unfinished Tasks

I have multiple heavy job calculation requests. The job may take different time. By using async and await I want to take the last requested result with canceling eventually unfinished previous tasks.
Currently I'm using BackGroundWorker with setting a job ID. I used only the the result with the last requested ID.
Can I rewrite the code with using async await?
private int backtestId;
private void PrepareStrategyCalculation()
{
backtestId = backtestManager.GetNextBacktestId();
strategy.BacktestId = backtestId;
backtestManager.StartBacktestWorker(strategy.Clone());
}
private void BacktestManager_StrategyBacktested(object sender, StrategyBacktestEventArgs e)
{
if (e.BacktestObject.Strategy.BacktestId != backtestId) return;
var calculatedStrategy = e.BacktestObject.Strategy;
...
}
EDIT:
Is this a solution?
private int backtestId;
private async void PrepareStrategyCalculation()
{
backtestId = backtestManager.GetNextBacktestId();
strategy.BacktestId = backtestId;
var calculatedStrategy = await backtestManager.StartBacktestAsync(strategy.Clone());
if (calculatedStrategy.BacktestId != backtestId) return;
...
}
Assuming your code is CPU-bound, then Task.Run is a suitable substitute for BackgroundWorker.
You can use CancellationTokenSource to cancel tasks. So, something like this would work, assuming that StartBacktestAsync is called from a single-threaded context such as a UI thread:
private CancellationTokenSource _cts;
async Task StartBacktestAsync()
{
if (_cts != null)
_cts.Cancel();
_cts = new CancellationTokenSource();
try
{
var token = _cts.Token;
await Task.Run(() => Backtest(token));
}
catch (OperationCanceledException)
{
// Any special logic for a canceled operation.
}
}
void Backtest(CancellationToken token)
{
... // periodically call token.ThrowIfCancellationRequested();
}

Can I wrap Task.Run under another Task.Run()?

I have a method HandleAcceptedConnection that is under Task.Run() that i want to run asynchronously(in another separate thread). I tried declaring HandleAcceptedConnection as async method and dont call await but it doesnt seem to run asynchronously. I can confirm that I can have Task.Run()(by watching the thread id) under another Task.Run() but is that recommended?
private async void Start_Click(object sender, RoutedEventArgs e)
{
var task = Task.Run(() =>
{
while (isContinue)
{
var handler = listener.Accept();
// handle connection
Log("Before");
Log("ThreadId Accept " + Thread.CurrentThread.ManagedThreadId);
// i want to run method below asynchronously. i want to
// wrap it under Task.Run() but i am already under
// Task.Run(). i set HandleAcceptedConnection as async. i thought by not
// calling await on HandleAcceptedConnection, HandleAcceptedConnection
// is asynchronous
HandleAcceptedConnection(handler);
Log("After");
isContinue = true;
}
});
await task;
}
private async Task HandleAcceptedConnection(Socket handler)
{
Log("ThreadId HandleAcceptedConnection " + Thread.CurrentThread.ManagedThreadId);
Log("Under HandleAcceptedConnection");
Thread.Sleep(10000);
}
When i run this, logs says
Before
Under HandleAcceptedConnection
After
i want
Before
After
Under HandleAcceptedConnection
i want HandleAcceptedConnection to be run asynchronously. Should i wrap it under another Task.Run or it is already asynchronous?
Did you try
private async Task HandleAcceptedConnection(Socket handler)
{
Thread.Sleep(1000);
Log("Under HandleAcceptedConnection");
}
Because doing something on another thread doesn't mean it'll be delayed.
You should be using AcceptTcpClientAsync, then you won't need extra threads. Check this answer for an example. Don't use a synchronous API when there is a naturally asynchronous version of it available.
Updated to address the comment. Nothing prevents you from using Task.Run from inside Task.Run, you code might look like this (untested):
private async void Start_Click(object sender, RoutedEventArgs e)
{
var connectionTasks = new List<Task>();
Func<Task> handleConnection = async () =>
{
var connectionTask = Task.Run(() => HandleAcceptedConnection(handler));
connectionTasks.Add(connectionTask);
await connectionTask;
connectionTasks.Remove(connectionTask);
};
var task = Task.Run(() =>
{
while (isContinue)
{
var handler = listener.Accept();
// handle connection
Log("Before");
Log("ThreadId Accept " + Thread.CurrentThread.ManagedThreadId);
var connectionTask = handleConnection();
Log("After");
isContinue = true;
}
});
await task;
}

How to serialize async/await?

Let's suppose I have this simple snippet:
async void button_Click(object sender, RoutedEventArgs e)
{
await Task.Factory.StartNew(() =>
{
Console.WriteLine("start");
Thread.Sleep(5000);
Console.WriteLine("end");
});
}
Obviously, everytime I push that button a new task is started even when a previous task still runs. How would I postpone any new task until all previous tasks have finished?
Some more details:
In the example above, each new task is identical to the task before. However, in the original context the sequence of tasks matters: Parameters may change (I could "simulate" it by using DateTime.Now.Ticks).
The tasks should be executed in the order they are "registered". Specificly, my program will talk to a serial device. I've done this before with a background thread utilizing a BlockingCollection. However, this time there's a strict request/response-protocol and I'd like to use async/await if it is possible.
Possible solution:
I could imagine creating tasks and storing them in a list. But how would I execute the tasks with respect to the requirements? Or should I return to the thread-based solution I have used before?
I recommend using a SemaphoreSlim for synchronization. However, you want to avoid Task.Factory.StartNew (as I explain on my blog), and also definitely avoid async void (as I explain in the MSDN article).
private SemaphoreSlim _mutex = new SemaphoreSlim(1);
async void button_Click(object sender, RoutedEventArgs e)
{
await Task.Run(async () =>
{
await _mutex.WaitAsync();
try
{
Console.WriteLine("start");
Thread.Sleep(5000);
Console.WriteLine("end");
}
finally
{
_mutex.Release();
}
});
}
You could wait on a SemaphoreSlim asynchronously and release it once the job is done. Don't forget to configure the semaphore initialcount to 1.
private static SemaphoreSlim semaphore = new SemaphoreSlim(1);
private async static void DoSomethingAsync()
{
await semaphore.WaitAsync();
try
{
await Task.Factory.StartNew(() =>
{
Console.WriteLine("start");
Thread.Sleep(5000);
Console.WriteLine("end");
});
}
finally
{
semaphore.Release();
}
}
private static void Main(string[] args)
{
DoSomethingAsync();
DoSomethingAsync();
Console.Read();
}
What about trying the Dataflow.ActionBlock<T> with the (default) max degree of parallelism of 1. This way you don't need to worry about any of the thread safety / locking concerns.
It could look something like:
...
var _block = new ActionBlock<bool>(async b =>
{
Console.WriteLine("start");
await Task.Delay(5000);
Console.WriteLine("end");
});
...
async void button_Click(object sender, RoutedEventArgs e)
{
await _block.SendAsync(true);
}
You could also setup the ActionBlock to receive a Task or Func<Task>, and simply run / await this input. Which would allow multiple operations to be queued and awaited from different sources.
I might be missing something, but I don't think SemaphoreSlim is needed for the OP's scenario. I'd do it the following way. Basically, the code just await the previous pending instance of the task before continuing (no exception handling for clarity):
// the current pending task (initially a completed stub)
Task _pendingTask = Task.FromResult<bool>(true);
async void button_Click(object sender, RoutedEventArgs e)
{
var previousTask = _pendingTask;
_pendingTask = Task.Run(async () =>
{
await previousTask;
Console.WriteLine("start");
Thread.Sleep(5000);
Console.WriteLine("end");
});
// the following "await" is optional,
// you only need it if you have other things to do
// inside "button_Click" when "_pendingTask" is completed
await _pendingTask;
}
[UPDATE] To address the comment, here's a thread-safe version, when button_Click can be called concurrently:
Task _pendingTask = Task.FromResult<bool>(true);
object _pendingTaskLock = new Object();
async void button_Click(object sender, RoutedEventArgs e)
{
Task thisTask;
lock (_pendingTaskLock)
{
var previousTask = _pendingTask;
// note the "Task.Run" lambda doesn't stay in the lock
thisTask = Task.Run(async () =>
{
await previousTask;
Console.WriteLine("start");
Thread.Sleep(5000);
Console.WriteLine("end");
});
_pendingTask = thisTask;
}
await thisTask;
}

Categories

Resources