I am storing the state of my data model. I clone the data model and then want to have it written to \"disk\" asynchronously.
Should I be using Task.Run() which runs it o
I don't think it matters. As far as I know, both methods get dispatched to a thread in the thread pool.
Using async
will make the async method run on a background thread and continue on the thread that started it when the async method is finished. You can imagine the compiler seeing the await keyword, put the awaited method in a background thread and wiring up events to notice when the asynch method is finished. Therefore this might be the better choice if you want to show a UI change because of the successful save, and because this is lesser code of course.
Task.Run()
would be nicer when you for any reason don't want to put the code in an async
method, for example because you want the calling method itself not be async. Also, there's lesser event marshaling involved, but I heavily doubt that there's any performance difference at all.
You should use Task.Run
for CPU-based work that you want to run on a thread pool thread.
In your situation, you want to do I/O based work without blocking the UI, so Task.Run
won't get you anything (unless you don't have asynchronous I/O APIs available).
As a side note, you definitely do want to await
this work. This makes error handling much cleaner.
So, something like this should suffice:
async void buttonSaveClick(..)
{
buttonSave.Enabled = false;
try
{
await myModel.Clone().SaveAsync();
}
catch (Exception ex)
{
// Display error.
}
buttonSave.Enabled = true;
}