I'm trying to write a hardware library in C# using the async / await features. For many operations, there will be two methods, one that runs asynchronously, and another one running the asynchronous method synchronously. For example, consider this:
public override bool ReferenceRun(bool positiveDirection) {
var runTask = ReferenceRunAsync(positiveDirection);
return runTask.Result;
}
public override async Task<bool> ReferenceRunAsync(bool positiveDirection) {
String cmd = createAxisCommand(positiveDirection ? refRunPlusCmd : refRunMinusCmd);
bool writeOK = writeToCOMPort(cmd);
if ( !writeOK ) return false;
return await Task.Factory.StartNew(() => {
WaitForHalt();
return setParameter(postitionParam, 0);
});
}
Form this and that answers, I suspected that it was ok to call runTask.Result
in order to wait for the async method to complete and then retrieve the result. However, when I run the code, the call to ReferenceRun
does never return. When I pause execution in the debugger, I can see that it hangs at the return runTask.Result
statement.
What's going on here?
Edit: According to this, the requested behavior can be achieved like this:
public override bool ReferenceRun(bool positiveDirection) {
var runTask = Task<bool>.Run(async () => { return await ReferenceRunAsync(positiveDirection); });
return runTask.Result;
}