Please refer below for the several options to call a function with async/await.
I put my questions below each option.
Lets assume I have a 3rd party Dll and want to call a function of it asynchronously. Despite there is a function description one cannot know what actually happens inside:
void DllTestFunction(Dictionary<Int32, double> dataMsgs);
First attempt to call that function asynchronously:
public class DriverTestViewModel
{
private readonly Dictionary<Int32, double> _dataDictionaryForDll;
private async Task CallDllTestFunctionAsync()
{
await Task.Run(() => DllTestFunction(_dataDictionaryForDll)).ConfigureAwait(
false );
}
}
Q1: Is there anything wrong yet in the attempt to encapsulate the "ordinary" function in an async call? I'm asking that since I found trivial examples only yet. E.g.:
await Task.Delay(TimeSpan.FromSeconds(2));
await SourceStream.ReadAsync(result, 0, (int)SourceStream.Length);
Both trivial examples are not calling Task.Run() or Task.Start(), which is pretty confusing.
Q2: I assume this is done inside Task.Delay() and FileStream.ReadAsync(), is it?
But there is more to ask:
var dllTask = Task.Run(() => DllTestFunction(_dataDictionaryForDll));
await dllTask.ConfigureAwait( false );
Q3: I assume both implementation options 1 and 2 are fully equivalent, are they?
Then one can split up more:
var dllTask = Task.Run(() => DllTestFunction(_dataDictionaryForDll));
dllTask.ConfigureAwait(false);
await dllTask;
A compiler warning is issued stating that the call is not awaited.
Q4: Why is that and can the warning be safely ignored as long as the await call follows?
Finally the option 3, the task is created on its own and Start() is used on the instance rather than the shared Task.Run() call.
var dllTask = new Task(() => DllTestFunction(_dataDictionaryForDll));
dllTask.Start();
await dllTask.ConfigureAwait( false );
Q5: I assume implementation options 1,2 and 3 are equivalent regarding the async processing, are they?
Q6: What is the difference in executing functions A,B,C in a row as illustrated in the example below?
Q7: When should the shared call be avoided?
A.Start();
B.Start();
C.Start();
Task.Run(A);
Task.Run(B);
Task.Run(C);