I have a method called StartAsync which await different task, this is the design:
public async Task StartAsync(int instance)
{
await SomeController.Foo();
await AnotherController.Foo2();
}
Now I need to run the StartAsync method multiple times, so I have created different Task, in this way I can manage a single execution of the Task of StartAsync:
Task bot1 = new Task(async () => { await new Bot().StartAsync(1); });
Task bot2 = new Task(async () => { await new Bot().StartAsync(2); });
these Tasks can be started by the input, essentially, if the user press 1 then the bot1 Task will start:
public async Task<bool> StartBotInstanceAsync(int instance)
{
try
{
switch(instance)
{
case 1:
await bot1.Start(); //<- Problem here
break;
case 2:
bot2.Start();
break;
}
return true;
}
catch(Exception ex)
{
Logger.Info(ex.ToString());
return false;
}
}
Essentially I need to write a log when an exception happen in side the try catch block, but for doing this I need to await the Task result, unfortunately I get this error:
Cannot await void
on await bot1.Start();
How can I manage the exception in this type of situation?
If you wish to do it with your current structure then you will need 2 separate statements.
case 1:
bot1.Start();
await bot1;
break;
If you want to use multiple bot instances, store them in an array and use the instance parameter as the index, eg :
_bots=new[]{ new Bot(),new Bot()};
public async Task<bool> StartBotInstanceAsync(int instance)
{
try
{
await _bots[instance-1].StartAsync();
return true;
}
catch(Exception ex)
{
Logger.Info(ex.ToString());
return false;
}
}
Or even better :
public async Task<bool> StartBotInstanceAsync(Bot bot)
{
try
{
await bot.StartAsync();
return true;
}
catch(Exception ex)
{
Logger.Info(ex.ToString());
return false;
}
}
var myBot=_bots[instance-1];
var started=await StartBotInstanceAsync(myBot);
More complex flows can be created easily by using async functions that take the bot as a parameter, eg :
public async Task SomeComplexFlow(Bot bot)
{
try
{
await bot.StartAsync();
await bot.DoSomething();
...
}
catch(Exception exc)
{
...
}
}
var myBot=_bots[instance-1];
await SomeComplexFlow(myBot);
It's possible to await multiple tasks for completion too. One coud use Task.WhenAll to wait for all bots to terminate, eg :
await Task.WhenAll(_bots[0].StopAsync()...);
Or, better yet :
var tasks=_bots.Select(bot=>bot.StopAsync());
await Tasks.WhenAll(tasks);
Related
I expected the following Connected and Disconnected handlers are called alternately.
But it wasn't. It is not 100% reproducible but sometimes the test failed. Repository is here.
I attach simplified code here because full code will be long. Please refer to the repository for the reproducible example.
public class ClientStressTest3 {
[Fact]
public async Task TestAsync() {
var client = new Client();
int openCloseDifference = 0;
var failures = Channel.CreateUnbounded<string>();
client.Connected += () => {
Interlocked.Increment(ref openCloseDifference);
int difference = openCloseDifference;
Debug.WriteLine("Connected: {}", difference);
if (Math.Abs(difference) > 1) {
// Failure point. Why enter here?
_ = failures.Writer.WriteAsync($"open close difference {difference}");
}
};
client.Disconnected += () => {
Interlocked.Decrement(ref openCloseDifference);
int difference = openCloseDifference;
Debug.WriteLine("Disconnected: {}", difference);
if (Math.Abs(difference) > 1) {
_ = failures.Writer.WriteAsync($"open close difference {difference}");
}
};
var tasks = new List<Task>();
for (int i = 0; i < 625; i++) {
tasks.Add(Task.Run(async () => {
try {
await client.ConnectAsync().ConfigureAwait(false);
}
catch (Exception ex) { }
}));
tasks.Add(Task.Run(async () => {
try {
await client.CloseAsync().ConfigureAwait(false);
}
catch (Exception ex) { }
}));
}
await Task.WhenAll(tasks).ConfigureAwait(false);
while (await failures.Reader.WaitToReadAsync().ConfigureAwait(false)) {
string failure = await failures.Reader.ReadAsync().ConfigureAwait(false);
throw new Exception(failure);
}
}
}
class Client {
public event Action Connected = delegate { };
public event Action Disconnected = delegate { };
private readonly SemaphoreSlim _connectSemaphore = new(1);
private Task _dispatch = Task.CompletedTask;
private WebSocket _clientSocket;
public async Task ConnectAsync() {
await _connectSemaphore.WaitAsync().ConfigureAwait(false);
// _dispatch may be same among multiple threads if restored at the same time.
try {
await _clientSocket.ConnectAsync().ConfigureAwait(false);
if (_dispatch != null) {
_dispatch = _dispatch.ContinueWith((_) => DispatchEventAsync(), TaskScheduler.Default);
}
}
finally {
_connectSemaphore.Release();
}
}
private async Task DispatchEventAsync() {
try {
Connected();
}
catch (Exception exception) { }
try {
while (await events.WaitToReadAsync().ConfigureAwait(false)) {
DispatchEvent(await events.ReadAsync().ConfigureAwait(false));
}
}
catch (Exception exception) { }
try {
Disconnected();
}
catch (Exception ex) { }
}
}
I think _connectSemaphore will guard the inner code execution, and only one thread will execute DispatchEventAsync.
But it seems sometimes two threads enter DispatchEventAsync at the same time. I can't understand this.
ContinueWith is a low-level method with dangerous default behavior (link is to my blog). In this case, your code is not behaving how you think it should because ContinueWith (like StartNew) doesn't understand asynchronous delegates.
Specifically, the task returned from ContinueWith (the same task stored in _dispatch) will complete when DispatchEventAsync asynchronously yields (i.e., hits its first await that asynchronously waits). This is likely the call to WaitToReadAsync, which is after Connected and before Disconnected. So the _dispatch task completes after Connected and before Disconnected.
Ideally, you should avoid ContinueWith completely. Sometimes a local asynchronous method helps, e.g.:
public async Task ConnectAsync() {
await _connectSemaphore.WaitAsync().ConfigureAwait(false);
try {
await _clientSocket.ConnectAsync().ConfigureAwait(false);
if (_dispatch != null) {
_dispatch = ChainAsync(_dispatch);
}
}
finally {
_connectSemaphore.Release();
}
static async Task ChainAsync(Task dispatch)
{
await dispatch;
await DispatchEventAsync();
}
}
If you do want to continue using ContinueWith for some reason, then you can use Unwrap:
public async Task ConnectAsync() {
await _connectSemaphore.WaitAsync().ConfigureAwait(false);
try {
await _clientSocket.ConnectAsync().ConfigureAwait(false);
if (_dispatch != null) {
_dispatch = _dispatch.ContinueWith(_ => DispatchEventAsync(), TaskScheduler.Default)
.Unwrap();
}
}
finally {
_connectSemaphore.Release();
}
}
Using either of these approaches, the _dispatch task will now complete at the end of DispatchEventAsync.
I think _connectSemaphore will guard the inner code execution, and only one thread will execute DispatchEventAsync.
Nope. Because you don't wait or await _dispatch. The semaphore only protects starting the task. The execution of the task happens in the background sometime after you release the semaphore.
But I'm chaining it with ContinueWith. Isn't it sufficien
No. That just adds another task that runs after; it doesn't actually run the task or wait for it to complete. If you want to run the _dispatch and then another task while holding the semaphore, just
await _dispatch;
await DispatchEventAsync();
If I have a method where I want to perform some (potentially) long-running function and I want to put a limit on its execution time, I've been using this pattern (please pardon any errors in the code, typed by hand, not in an IDE, this is a simplification of a larger piece of code).
public string GetHello()
{
var task = Task.Run(() =>
{
// do something long running
return "Hello";
});
bool success = task.Wait(TimeSpan.FromMilliseconds(1000));
if (success)
{
return task.Result;
}
else
{
throw new TimeoutException("Timed out.");
}
}
If I want to use the GetHello method in an async capacity, i.e. public async Task<string> GetHello(), how would I do this while hopefully preserving a similar pattern? I have the following, but I get compiler warnings about This async method lacks 'await' operators and will run synchronously as expected.
public async Task<string> GetHello()
{
var task = Task.Run(async () =>
{
// await something long running
return "Hello";
});
bool success = task.Wait(TimeSpan.FromMilliseconds(1000));
if (success)
{
return task.Result;
}
else
{
throw new TimeoutException("Timed out.");
}
}
I just don't know how to change this or where I would put await in order for this to work as expected.
You can combine using CancellationToken and awaitable Task.WhenAny to achieve desired behavior:
public async Task<string> GetHello()
{
var cts = new CancellationTokenSource();
var task = Task.Run(async () =>
{
// await something long running and pass/use cts.Token here too
return "Hello";
}, cts.Token);
var delay = Task.Delay(1000, cts.Token);
var finishedFirst = await Task.WhenAny(task, delay);
cts.Cancel();
if (finishedFirst == task)
{
return task.Result;
}
else
{
throw new TimeoutException("Timed out.");
}
}
My assertion of acceptor.IsStarted.Should().BeTrue(); (see unit test below) always fails, as it's getting evaluated too early. The call to await task returns immediately and doesn't give this.acceptor.Start() enough time to spin up.
I would like to make the startup of my FixAcceptor() more deterministic and therefor introduced the parameter TimeSpan startupDelay.
However I simply have no clue where and how I can delay the startup.
Putting an additional Thread.Sleep(startupDelay) between this.acceptor.Start() and this.IsStarted = true won't help as it will only block the worker task itself, but not the calling thread.
I hope it's clear what I'd like to archive and what I am struggling with. Thanks in advance.
public class FixAcceptor
{
// Type provided by QuickFix.net
private readonly ThreadedSocketAcceptor acceptor;
public FixAcceptor(IFixSettings settings)
{
// Shortened
}
public bool IsStarted { get; private set; }
public async void Run(CancellationToken cancellationToken, TimeSpan startupDelay)
{
var task = Task.Run(() =>
{
cancellationToken.ThrowIfCancellationRequested();
this.acceptor.Start();
this.IsStarted = true;
while (true)
{
// Stop if token has been canceled
if (cancellationToken.IsCancellationRequested)
{
this.acceptor.Stop();
this.IsStarted = false;
cancellationToken.ThrowIfCancellationRequested();
}
// Save some CPU cycles
Thread.Sleep(TimeSpan.FromSeconds(1));
}
}, cancellationToken);
try
{
await task;
}
catch (OperationCanceledException e)
{
Debug.WriteLine(e.Message);
}
}
}
And the corresponding consumer code
[Fact]
public void Should_Run_Acceptor_And_Stop_By_CancelationToken()
{
// Arrange
var acceptor = new FixAcceptor(new FixAcceptorSettings("test_acceptor.cfg", this.logger));
var tokenSource = new CancellationTokenSource();
// Act
tokenSource.CancelAfter(TimeSpan.FromSeconds(10));
acceptor.Run(tokenSource.Token, TimeSpan.FromSeconds(3));
// Assert
acceptor.IsStarted.Should().BeTrue();
IsListeningOnTcpPort(9823).Should().BeTrue();
// Wait for cancel event to occur
Thread.Sleep(TimeSpan.FromSeconds(15));
acceptor.IsStarted.Should().BeFalse();
}
Adding time delays to achieve determinism is not a recommended practice. You can achieve 100% determinism by using a TaskCompletionSource for controlling the completion of a task at just the right moment:
public Task<bool> Start(CancellationToken cancellationToken)
{
var startTcs = new TaskCompletionSource<bool>();
var task = Task.Run(() =>
{
cancellationToken.ThrowIfCancellationRequested();
this.acceptor.Start();
this.IsStarted = true;
startTcs.TrySetResult(true); // Signal that the starting phase is completed
while (true)
{
// ...
}
}, cancellationToken);
HandleTaskCompletion();
return startTcs.Task;
async void HandleTaskCompletion() // async void method = should never throw
{
try
{
await task;
}
catch (OperationCanceledException ex)
{
Debug.WriteLine(ex.Message);
startTcs.TrySetResult(false); // Signal that start failed
}
catch
{
startTcs.TrySetResult(false); // Signal that start failed
}
}
}
Then replace this line in your test:
acceptor.Run(tokenSource.Token, TimeSpan.FromSeconds(3));
...with this one:
bool startResult = await acceptor.Start(tokenSource.Token);
Another issue that caught my eye is the bool IsStarted property which is mutated from one thread and observed by another, without synchronization. This is not really a problem because you could rely on the undocumented memory barrier that is inserted automatically on every await, and be quite confident that you'll not have visibility issues, but if you want to be extra sure you could synchronize the access by using a lock (most robust), or backup the property with a volatile private field like this:
private volatile bool _isStarted;
public bool IsStarted => _isStarted;
I would recommend that you structure your FixAcceptor.Run() methode a little bit different
public async Task Run(CancellationToken cancellationToken, TimeSpan startupDelay)
{
var task = Task.Run(async () =>
{
try
{
cancellationToken.ThrowIfCancellationRequested();
this.acceptor.Start();
this.IsStarted = true;
while (true)
{
// Stop if token has been canceled
if (cancellationToken.IsCancellationRequested)
{
this.acceptor.Stop();
this.IsStarted = false;
cancellationToken.ThrowIfCancellationRequested();
}
// Save some CPU cycles
await Task.Delay(TimeSpan.FromSeconds(1));
}
}
catch (OperationCanceledException e)
{
Debut.WriteLine(e.Message);
}
}, cancellationToken);
await Task.Delay(startupDelay);
}
so the exception handling is in the inner task and the Run methode returns a Task that completes after the startupDelay.
(I also exchanged the Thread.Sleep() with a Task.Delay())
Then in the test methode you can await the Task returned by Run
[Fact]
public async Task Should_Run_Acceptor_And_Stop_By_CancelationToken()
{
// Arrange
var acceptor = new FixAcceptor(new FixAcceptorSettings("test_acceptor.cfg", this.logger));
var tokenSource = new CancellationTokenSource();
// Act
tokenSource.CancelAfter(TimeSpan.FromSeconds(10));
await acceptor.Run(tokenSource.Token, TimeSpan.FromSeconds(3));
// Assert
acceptor.IsStarted.Should().BeTrue();
IsListeningOnTcpPort(9823).Should().BeTrue();
// Wait for cancel event to occur
Thread.Sleep(TimeSpan.FromSeconds(15));
acceptor.IsStarted.Should().BeFalse();
}
It should be okay to make the mehtode async (it seams like you use xunit)
I need to spawn some long running tasks in ASP.NET WebAPI, and I chose to do that using QueueBackgroundWorkItem.
My question is -
I need to implement a WhenAll mechanism with those tasks, meaning - I need to know when some tasks has finished, and then to perform some other task.
How can that be done using QueueBackgroundWorkItem? I couldn't find a way to do that, since it returns void, and accepts Action.
Thanks!
You can use TaskCompletionSource to create a helper method like this:
public static Task RunViaQueueBackgroundWorkItem(Action<CancellationToken> action)
{
TaskCompletionSource<int> tcs = new TaskCompletionSource<int>();
HostingEnvironment.QueueBackgroundWorkItem((ct) =>
{
try
{
action(ct);
if (ct.IsCancellationRequested)
tcs.TrySetCanceled();
else
tcs.TrySetResult(0);
}
catch (Exception ex)
{
tcs.TrySetException(ex);
}
});
return tcs.Task;
}
This method will return a task that will complete after the action completes. Note that it handles the case where an exception occurs during the invocation of the action. It also handles the case if cancellation is requested.
Here is an example of how you can use it:
public async Task<string> Get(int id)
{
var t1 = RunViaQueueBackgroundWorkItem(ct => DoSomeTask1(ct));
var t2 = RunViaQueueBackgroundWorkItem(ct => DoSomeTask2(ct));
await Task.WhenAll(t1, t2);
//...
}
For completeness, here is the helper method for the other overload of QueueBackgroundWorkItem:
public static Task RunViaQueueBackgroundWorkItem(Func<CancellationToken,Task> asyncAction)
{
TaskCompletionSource<int> tcs = new TaskCompletionSource<int>();
HostingEnvironment.QueueBackgroundWorkItem(async (ct) =>
{
try
{
await asyncAction(ct);
if (ct.IsCancellationRequested)
tcs.TrySetCanceled();
else
tcs.TrySetResult(0);
}
catch (Exception ex)
{
tcs.TrySetException(ex);
}
});
return tcs.Task;
}
I need to implement a WhenAll mechanism with those tasks, meaning - I need to know when some tasks has finished, and then to perform some other task.
What you should do is write up the logic you need:
async Task MyWorkAsync(CancellationToken token)
{
var t1 = Work1Async(token);
var t2 = Work2Async(token);
await Task.WhenAll(t1, t2);
... // More work
}
And then just call QueueBackgroundWorkItem once:
HostingEnvironment.QueueBackgroundWorkItem(token => MyWorkAsync(token));
I'm trying to wrap my Operations Contracts to the try-catch block. The problem is that my EF context destroyed in the same time scope. I guess the problem compiler doesn't know what to do properly. Also my catch block doesn't handle any exceptions. Sorry for my English, I hope my code show what I mean:
private static async Task<T> SurroundWithTryCatch<T>(Action t, T response) where T : BaseResponse
{
try
{
await Task.Run(t);
}
catch (Exception e)
{
response.Success = false;
response.Errors.Add(e.Message);
}
return response;
}
public async Task<CreateResponse> CreateAsync(CreateRequest request)
{
var response = new CreateResponse();
return await SurroundWithTryCatch(async delegate
{
var newUser = new ApplicationUser { UserName = request.UserName, Email = request.Email };
await Database.UserManager.CreateAsync(newUser, request.Password);
//Some another logic...
await Database.CommitAsync();
}, response);
}
The problem in the second line of CreateAsync method. UserManager was cleaned by GC earlier. So I have ObjectDisposedException. Database is the IUnitOfWork implementation and injected by Autofac.
You're breaking the await chain - t no longer returns a task. Since you no longer have a task, the execution will continue after the first await, rather than after the whole method is done. Think of await as return - if you don't return (and await/wait for) a Task, you lose your chance at synchronization.
Instead, you want to pass Func<Task>, and await it directly:
private static async Task<T> SurroundWithTryCatch<T>(Func<Task> t, T response) where T : BaseResponse
{
try
{
await t();
}
catch (Exception e)
{
response.Success = false;
response.Errors.Add(e.Message);
}
return response;
}
public async Task<CreateResponse> CreateAsync(CreateRequest request)
{
var response = new CreateResponse();
return await SurroundWithTryCatch(async () =>
{
var newUser = new ApplicationUser { UserName = request.UserName, Email = request.Email };
await Database.UserManager.CreateAsync(newUser, request.Password);
//Some another logic...
await Database.CommitAsync();
}, response);
}
Task.Run also works, but you probably don't want that anyway - your code is asynchronous, and (a guess) you're running in a ASP.NET request, so there's no benefit to launching a task just to wait on the result of another task. Task.Run is used for doing CPU work in a separate thread, something you usually want to avoid in ASP.NET.