Async, await in C# - c#

On closing of my application I have to do some clean up activity and I have written something like this in ClassA.cs
protected override void OnExit(ExitEventArgs e)
{
Cleanup();
base.OnExit(e);
}
private async Task Cleanup()
{
GC.Collect();
GC.WaitForPendingFinalizers();
if (databaseInitialisation != null)
{
await databaseInitialisation.InitialiseDatabase();
}
databaseFile?.Dispose();
}
I have one more class ClassB.cs
public class DatabaseInitialisation : IDatabaseInitialisation
{
private readonly string filterOptimisationPath;
private readonly Task databaseInitialisation;
private IDbConnectionFactory ConnectionFactory { get; }
public async Task InitialiseDatabase() => await databaseInitialisation;
public DatabaseInitialisation(string databaseFilePath, string filterOptimisationPath)
{
this.filterOptimisationPath = filterOptimisationPath;
ConnectionFactory = new SqLiteConnectionFactory(databaseFilePath);
databaseInitialisation = Task.Run(() => CreateDatabase(databaseFilePath));
}
}
so now when I close my application, sometimes when cleanup is called execution of the program going from await is going to onexit method without executing the dispose method

The root of your trouble is that you need to call an async method from a sync method, and you cannot make that method async because it's part of the GUI framework. The general advice here would be to make your calling method async, but since you can't, there are a few ways you can accomplish this:
Option 1 -- Task.Run
Change your OnExit method to launch Cleanup on a thread pool thread and then synchronously wait for that using GetAwaiter().GetResult() to prevent deadlocks. Since this is only running once at shutdown, it should be fine, but launching background threads like this would not be recommended if this were a method that will run often as it could potentially lead to thread pool starvation.
protected override void OnExit(ExitEventArgs e)
{
Task.Run(async () => await Cleanup().ConfigureAwait(false))
.GetAwaiter().GetResult();
base.OnExit(e);
}
Option 2 -- async void and a ManualResetEvent
This approach avoids using .GetAwaiter().GetResult() and launching on a thread pool thread, but any exception thrown in cleanup will cause the application to crash.
protected override void OnExit(ExitEventArgs e)
{
using var signal = new ManualResetEventSlim(false);
Cleanup(signal);
signal.Wait();
base.OnExit(e);
}
private async void Cleanup(ManualResetEventSlim signal)
{
if (databaseInitialisation != null)
{
await databaseInitialisation.InitialiseDatabase();
}
databaseFile?.Dispose();
signal.Set();
}
You could also use one of the Wait overloads to include a timeout.
As a side note, in a GUI application like this, you should really be calling .ConfigureAWait(false) on every task you await that isn't being called directly from a GUI event. Not doing so risks deadlocks.
One caveat to both these solutions is that if your Cleanup method or anything in its call stack, both of these methods will deadlock, and in that case, another solution is needed.

Related

Can I create a C# async method without using a different thread (Task)?

I have searched a lot and it seems C# async await has to be used together with Task.
The situation is that I have a method that is very time consuming which is OK, but I hope it won't block the main method.
So I describe the main method as "async", and inside it, I call and "await" the time consuming method, but C# need the time consuming method to be included in a Task which means it will be executed in a seperate thread. But that method has something that cannot run outside main thread.
And my question is how can I run the time consuming method asynchronously without putting it in a different thread?
Thank you very much.
PS: I'm doing this in Unity3D, is it possible to leverage Coroutine to reach the goal?
//main method
private async void MainMethod()
{
//...
bool result = await TimeConsumingMethod();
//...
}
//time consuming method
private async Task<bool> TimeConsumingMethod()
{
bool result;
await Task.Run(()=>
{
//...
//SOME CODE THAT CANNOT run in thread other than main
//...
});
return result;
}
To run anything aysnchronously (not blocking the main thread) in unity you have to use a different Thread/Task.
But as you also want to run code on the main thread in that separate thread you'll have to communicate between the two.
Although you can't run anything on the main thread from inside a different thread. You can make a queue that the main thread consistently handles. When the off thread then wants to do something on the main thread it adds it to the queue and the mainThreadHandler will then handle it in the next frame update. So the off thread can then tell the main thread that it wants to do something on the main thread and wait for the main thread to be done with that code and then continue with the processing after.
This is an implementation of a main thread handler:
public class MainThreadHandler:MonoBehaviour
{
private static readonly Queue<Action> _executionQueue = new Queue<Action>();
public void Update()
{
lock (_executionQueue)
{
while (_executionQueue.Count > 0)
{
_executionQueue.Dequeue().Invoke();
}
}
}
public static void Enqueue(Action action)
{
lock (_executionQueue)
{
_executionQueue.Enqueue(action);
}
}
}
Calling your code including calling things in the main thread and then waiting for it will then look something like this:
private Task currentTask;
private bool taskResult;
public void StartOffThreadMethod()
{
currentTask = Task.Run(() =>
{
DoCalculationsOffThread();
bool isMainThreadDone = false;
MainThreadHandler.Enqueue(() =>
{
//Main thread code
//Either set a bool that the off thread checks to see if the action has been completed
//or start a new task that handles the rest of the off threaded code
//This example uses a isDone bool
isMainThreadDone = true;
});
while (!isMainThreadDone)
{
Thread.Sleep(100);
}
DoOtherCalculationsOffThread();
taskResult = true;
});
}
private void Update()
{
if (currentTask != null && currentTask.IsCompleted)
{
//do stuff with the result
}
}
I'd also like to add that going back and forth between the main thread and an calculating thread can be rather tricky business. If it can be prevented i would try to prevent it.

One line fire and forget: void vs. async void + await

I have a void event handler that consists of exactly one line that's a call to an awaitable method.
void Handler( object sender, EventArgs args ) => AwaitableMethod();
Changing the return type to Task isn't an option, so it's fire-and-forget no matter the syntactic sugar. Even so, Visual Studio puts a green squiggly under the unawaited call, suggesting I make the handler async void and await the call.
async void Handler( object sender, EventArgs args ) => await AwaitableMethod();
My understanding is that adding async void and await in this case would just be useless overhead. Does Visual Studio know something that I don't know, or is it just being unnecessarily annoying?
My understanding is that adding async void and await in this case would just be useless overhead.
No.
If Handler returned a Task, then that would be true and eliding async/await would be fine; the code without async/await would just return the Task directly instead of "unwrapping" it with await and "wrapping" it back into a Task with async.
However, that's not the case here; Handler returns void, so the code without async/await will just ignore the returned Task, which is wrong the vast majority of the time (hence the compiler warning). Specifically, ignoring the Task will ignore any exceptions from that Task. It's also not possible for your code to know when an ignored Task has completed, but presumably that's acceptable since your handler is returning void.
There is a "registration" that async void methods do so that the framework is aware there is a task still in progress, so the framework knows when it's safe to shut down. The only .NET provided framework that actually cares about that is ASP.NET pre-Core; all other .NET-provided frameworks (including all UI frameworks) ignore that "registration".
In this particular case, it depends mostly on your error handling.
If AwaitableMethod asynchronously throws, it will throw on the UI thread on the second version.
I would suggest to avoid event handlers in this case and use something like this instead if possible.
public class Eventful
{
private readonly List<Func<Task>> _handlers = new List<Func<Task>>();
public void AddHandler(Func<Task> handler) => _handlers.Add(handler);
private async Task RunHandlers()
{
foreach (var handler in _handlers)
{
await handler();
}
}
}
public class Consumer
{
public Consumer()
{
var eventful = new Eventful();
eventful.AddHandler(async () =>
{
await DoAsyncTask();
});
}
private static async Task DoAsyncTask()
{
await Task.CompletedTask;
}
}

How to invoke a method on specific running task

I'm new in the themes tasks.
How to get access to the right task and invoke the method on this task? The task has an ID and I gave a Name to it and I got a TaskScheduler.
I get the Exception, which is correct:
InvalidOperationException: The calling thread can not access this object because the object is owned by another thread.
Problem:
In the Main I start a Task with CustomSplashScreenViewModel.StartSplashScreenAsync(). More Tasks get startet and are running. With the Event when everything has loaded I need to Close my SplashScreen.
The method CustomSplashScreenViewModel.CloseSplash(_splashTask, _taskSchedulerSplash); get those informations. When I debug it, the _splashTask is "null" and in the _taskSchedulerSplash it has the _splashTask inside.
Inside the CloseSplash Method I like to invoke the method _view.Close() on the _splashTask.
How do I solve this?
public class Program
{
private static readonly SingleThreadTaskScheduler _taskSchedulerSplash = new SingleThreadTaskScheduler(ApartmentState.STA);
[ThreadStatic]
private static Task _splashTask;
// [STAThread]
public static async Task Main()
{
_splashTask = await Task.Factory.StartNew(() =>
{
return CustomSplashScreenViewModel.StartSplashScreenAsync();
}, _taskSchedulerSplash);
var taskScheduler = new SingleThreadTaskScheduler(ApartmentState.STA);
var taskList = new List<Task>();
var updateTask = Task.Run(InstallHelper.CheckForUpdatesAsync);
updateTask.Wait();
taskList.Add(updateTask);
var tasks = await Task.Factory.ContinueWhenAll(taskList.ToArray(), result => Task.Factory.StartNew( ()=>AppStart(container), taskScheduler));
tasks.Wait();
}
private static void App_MainWindowLoaded(object sender, EventArgs e)
{
CustomSplashScreenViewModel.CloseSplash(_splashTask, _taskSchedulerSplash);
}
}
public class CustomSplashScreenViewModel
{
private static Thread _currentThread;
public static void CloseSplash(Task task, TaskScheduler taskScheduler)
{
if (_view!= null)
{
// Here i need the right Task and to invoke the following method
// if I'm doing _view.Dispatcher.Invoke(new Action(_view.Close)); it doesn't
// work coz it's another STA Thread. Inside this class I can store the right task in
// a local variable. this works. But how to invoke it if the Task is already running?
// I like to overgive the task - may it isn't possible.
_view.Close();
}
}
}
Thanks a lot for helping me.
You can't change a running task. However, you can schedule another task that will run on the same scheduler, which should work just fine for what you need (it'll run on the same STA thread that owns the splash screen):
public static void CloseSplash(Task task, TaskScheduler taskScheduler)
{
if (_view!= null)
{
Task.Factory.StartNew(() => _view.Close(), taskScheduler);
}
}
On a side note, I'd recommend these to make the code easier to understand:
Introducing a TaskFactory instance for your custom task scheduler instead of using TaskScheduler with Task.Factory.
Avoid Task.Factory.ContinueWhenAll and Task.Wait; use Task.WhenAll and await instead.

ConfigureAwait(False) doesn't change context after ContinueWith()

I don't know if I am doing something wrong or I found a bug in the Async library, but I have seen an issue when running some async code after I came back to the Synchronized context with continueWith().
UPDATE: The code now runs
using System;
using System.ComponentModel;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
internal static class Program
{
[STAThread]
private static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
MainFrameController controller = new MainFrameController(this);
//First async call without continueWith
controller.DoWork();
//Second async call with continueWith
controller.DoAsyncWork();
}
public void Callback(Task<HttpResponseMessage> task)
{
Console.Write(task.Result); //IT WORKS
MainFrameController controller =
new MainFrameController(this);
//third async call
controller.DoWork(); //IT WILL DEADLOCK, since ConfigureAwait(false) in HttpClient DOESN'T change context
}
}
internal class MainFrameController
{
private readonly Form1 form;
public MainFrameController(Form1 form)
{
this.form = form;
}
public void DoAsyncWork()
{
Task<HttpResponseMessage> task = Task<HttpResponseMessage>.Factory.StartNew(() => DoWork());
CallbackWithAsyncResult(task);
}
private void CallbackWithAsyncResult(Task<HttpResponseMessage> asyncPrerequisiteCheck)
{
asyncPrerequisiteCheck.ContinueWith(task =>
form.Callback(task),
TaskScheduler.FromCurrentSynchronizationContext());
}
public HttpResponseMessage DoWork()
{
MyHttpClient myClient = new MyHttpClient();
return myClient.RunAsyncGet().Result;
}
}
internal class MyHttpClient
{
public async Task<HttpResponseMessage> RunAsyncGet()
{
HttpClient client = new HttpClient();
return await client.GetAsync("https://www.google.no").ConfigureAwait(false);
}
}
partial class Form1
{
private IContainer components;
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Text = "Form1";
}
#endregion
}
}
The HttpClient code which is async runs well the first time.
Then, I run the second async code and return to the UI context with ContinueWith, and it works well.
I run the HttClient code again, but it deadlock because this time ConfigureAwait(false) does not change the context.
The main problem in your code is due to StartNew and ContinueWith. ContinueWith is dangerous for the same reasons that StartNew is dangerous, as I describe on my blog.
In summary: StartNew and ContinueWith should only be used if you're doing dynamic task-based parallelism (which this code is not).
The actual problem is that HttpClient.GetAsync doesn't use (the equivalent of) ConfigureAwait(false); it's using ContinueWith with its the default scheduler argument (which is TaskScheduler.Current, not TaskScheduler.Default).
To explain in more detail...
The default scheduler for StartNew and ContinueWith is not TaskScheduler.Default (the thread pool); it's TaskScheduler.Current (the current task scheduler). So, in your code, DoAsyncWork as it currently is does not always execute DoWork on the thread pool.
The first time DoAsyncWork is called, it will be called on the UI thread but without a current TaskScheduler. In this case, TaskScheduler.Current is the same as TaskScheduler.Default, and DoWork is called on the thread pool.
Then, CallbackWithAsyncResult invokes Form1.Callback with a TaskScheduler that runs it on the UI thread. So, when Form1.Callback calls DoAsyncWork, it is called on the UI thread with a current TaskScheduler (the UI task scheduler). In this case, TaskScheduler.Current is the UI task scheduler, and DoAsyncWork ends up calling DoWork on the UI thread.
For this reason, you should always specify a TaskScheduler when calling StartNew or ContinueWith.
So, this is a problem. But it's not actually causing the deadlock you're seeing, because ConfigureAwait(false) should allow this code to just block the UI instead of deadlocking.
It's deadlocking because Microsoft made the same mistake. Check out line 198 here: GetContentAsync (which is called by GetAsync) uses ContinueWith without specifying a scheduler. So, it's picking up the TaskScheduler.Current from your code, and will not ever complete its task until it can run on that scheduler (i.e., the UI thread), causing the classic deadlock.
There's nothing you can do to fix the HttpClient.GetAsync bug (obviously). You'll just have to work around it, and the easiest way to do that is to avoid having a TaskScheduler.Current. Ever, if you can.
Here's some general guidelines for asynchronous code:
Don't ever use StartNew. Use Task.Run instead.
Don't ever use ContinueWith. Use await instead.
Don't ever use Result. Use await instead.
If we just do minimal changes (replacing StartNew with Run and ContinueWith with await), then DoAsyncWork always executes DoWork on the thread pool, and the deadlock is avoided (since await uses the SynchronizationContext directly and not a TaskScheduler):
public void DoAsyncWork()
{
Task<HttpResponseMessage> task = Task.Run(() => DoWork());
CallbackWithAsyncResult(task);
}
private async void CallbackWithAsyncResult(Task<HttpResponseMessage> asyncPrerequisiteCheck)
{
try
{
await asyncPrerequisiteCheck;
}
finally
{
form.Callback(asyncPrerequisiteCheck);
}
}
However, it's always questionable to have a callback scenario with Task-based asynchrony, because Tasks themselves have the power of callbacks within them. It looks like you're trying to do a sort of asynchronous initialization; I have a blog post on asynchronous construction that shows a few possible approaches.
Even something really basic like this would be a better design than callbacks (again, IMO), even though it uses async void for initialization:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
MainFrameController controller = new MainFrameController();
controller.DoWork();
Callback(controller.DoAsyncWork());
}
private async void Callback(Task<HttpResponseMessage> task)
{
await task;
Console.Write(task.Result);
MainFrameController controller = new MainFrameController();
controller.DoWork();
}
}
internal class MainFrameController
{
public Task<HttpResponseMessage> DoAsyncWork()
{
return Task.Run(() => DoWork());
}
public HttpResponseMessage DoWork()
{
MyHttpClient myClient = new MyHttpClient();
var task = myClient.RunAsyncGet();
return task.Result;
}
}
Of course, there's other design problems here: namely, DoWork is blocking on a naturally-asynchronous operation, and DoAsyncWork is blocking a thread pool thread on a naturally-asynchronous operation. So, when Form1 calls DoAsyncWork, it's awaiting a thread pool task that's blocked on an asynchronous operation. Async-over-sync-over-async, that is. You may also benefit from my blog series on Task.Run etiquette.
Don't use .Result. If you have any code at all that uses async/await, just completely forget it even exists. Even if we get it working today, what you are trying to do will be so incredibly brittle that it won't necessarily work tomorrow.

How does nunit successfully wait for async void methods to complete?

When using async/await in C#, the general rule is to avoid async void as that's pretty much a fire and forget, rather a Task should be used if no return value is sent from the method. Makes sense. What's strange though is that earlier in the week I was writing some unit tests for a few async methods I wrote, and noticed that NUnit suggested to mark the async tests as either void or returning Task. I then tried it, and sure enough, it worked. This seemed really strange, as how would the nunit framework be able to run the method and wait for all asynchronous operations to complete? If it returns Task, it can just await the task, and then do what it needs to do, but how can it pull it off if it returns void?
So I cracked open the source code and found it. I can reproduce it in a small sample, but I simply cannot make sense of what they're doing. I guess I don't know enough about the SynchronizationContext and how that works. Here's the code:
class Program
{
static void Main(string[] args)
{
RunVoidAsyncAndWait();
Console.WriteLine("Press any key to continue. . .");
Console.ReadKey(true);
}
private static void RunVoidAsyncAndWait()
{
var previousContext = SynchronizationContext.Current;
var currentContext = new AsyncSynchronizationContext();
SynchronizationContext.SetSynchronizationContext(currentContext);
try
{
var myClass = new MyClass();
var method = myClass.GetType().GetMethod("AsyncMethod");
var result = method.Invoke(myClass, null);
currentContext.WaitForPendingOperationsToComplete();
}
finally
{
SynchronizationContext.SetSynchronizationContext(previousContext);
}
}
}
public class MyClass
{
public async void AsyncMethod()
{
var t = Task.Factory.StartNew(() =>
{
Thread.Sleep(1000);
Console.WriteLine("Done sleeping!");
});
await t;
Console.WriteLine("Done awaiting");
}
}
public class AsyncSynchronizationContext : SynchronizationContext
{
private int _operationCount;
private readonly AsyncOperationQueue _operations = new AsyncOperationQueue();
public override void Post(SendOrPostCallback d, object state)
{
_operations.Enqueue(new AsyncOperation(d, state));
}
public override void OperationStarted()
{
Interlocked.Increment(ref _operationCount);
base.OperationStarted();
}
public override void OperationCompleted()
{
if (Interlocked.Decrement(ref _operationCount) == 0)
_operations.MarkAsComplete();
base.OperationCompleted();
}
public void WaitForPendingOperationsToComplete()
{
_operations.InvokeAll();
}
private class AsyncOperationQueue
{
private bool _run = true;
private readonly Queue _operations = Queue.Synchronized(new Queue());
private readonly AutoResetEvent _operationsAvailable = new AutoResetEvent(false);
public void Enqueue(AsyncOperation asyncOperation)
{
_operations.Enqueue(asyncOperation);
_operationsAvailable.Set();
}
public void MarkAsComplete()
{
_run = false;
_operationsAvailable.Set();
}
public void InvokeAll()
{
while (_run)
{
InvokePendingOperations();
_operationsAvailable.WaitOne();
}
InvokePendingOperations();
}
private void InvokePendingOperations()
{
while (_operations.Count > 0)
{
AsyncOperation operation = (AsyncOperation)_operations.Dequeue();
operation.Invoke();
}
}
}
private class AsyncOperation
{
private readonly SendOrPostCallback _action;
private readonly object _state;
public AsyncOperation(SendOrPostCallback action, object state)
{
_action = action;
_state = state;
}
public void Invoke()
{
_action(_state);
}
}
}
When running the above code, you'll notice that the Done Sleeping and Done awaiting messages show up before the Press any key to continue message, which means the async method is somehow being waited on.
My question is, can someone care to explain what's happening here? What exactly is the SynchronizationContext (I know it's used to post work from one thread to another) but I'm still confused as to how we can wait for all the work to be done. Thanks in advance!!
A SynchronizationContext allows posting work to a queue that is processed by another thread (or by a thread pool) -- usually the message loop of the UI framework is used for this.
The async/await feature internally uses the current synchronization context to return to the correct thread after the task you were waiting for has completed.
The AsyncSynchronizationContext class implements its own message loop. Work that is posted to this context gets added to a queue.
When your program calls WaitForPendingOperationsToComplete();, that method runs a message loop by grabbing work from the queue and executing it.
If you set a breakpoint on Console.WriteLine("Done awaiting");, you will see that it runs on the main thread within the WaitForPendingOperationsToComplete() method.
Additionally, the async/await feature calls the OperationStarted() / OperationCompleted() methods to notify the SynchronizationContext whenever an async void method starts or finishes executing.
The AsyncSynchronizationContext uses these notifications to keep a count of the number of async methods that are running and haven't completed yet. When this count reaches zero, the WaitForPendingOperationsToComplete() method stops running the message loop, and the control flow returns to the caller.
To view this process in the debugger, set breakpoints in the Post, OperationStarted and OperationCompleted methods of the synchronization context. Then step through the AsyncMethod call:
When AsyncMethod is called, .NET first calls OperationStarted()
This sets the _operationCount to 1.
Then the body of AsyncMethod starts running (and starts the background task)
At the await statement, AsyncMethod yields control as the task is not yet complete
currentContext.WaitForPendingOperationsToComplete(); gets called
No operations are available in the queue yet, so the main thread goes to sleep at _operationsAvailable.WaitOne();
On the background thread:
at some point the task finishes sleeping
Output: Done sleeping!
the delegate finishes execution and the task gets marked as complete
the Post() method gets called, enqueuing a continuation that represents the remainder of the AsyncMethod
The main thread wakes up because the queue is no longer empty
The message loop runs the continuation, thus resuming execution of AsyncMethod
Output: Done awaiting
AsyncMethod finishes execution, causing .NET to call OperationComplete()
the _operationCount is decremented to 0, which marks the message loop as complete
Control returns to the message loop
The message loop finishes because it was marked as complete, and WaitForPendingOperationsToComplete returns to the caller
Output: Press any key to continue. . .

Categories

Resources