I have a stack of calls to a web api that need to be called asynchronously. I have never used the aysnc.
I have created a simple test console program, along the lines of :
class Program
{
static void Main(string[] args)
{
ClassOne xx = new ClassOne();
var v1 = xx.DummyTask();
}
}
With the class defined as :
namespace GHTest.classes
{
public class ClassOne
{
GitHubClient client;
public ClassOne()
{
client = new GitHubClient(new ProductHeaderValue("OMHSite"));
}
public async Task<string> DummyTask()
{
Task<Repository> task = client.Repository.Get("openEHR", "CKM-mirror");
task.Wait();
var myResult = task.Result;
return myResult.FullName;
}
}
}
Visual Studio states I should use the "await" operator as currently this code will run synchronously. Where does the await operator go?
Furthermore if the following statement throws an exception, how do I catch that in the task
client.Repository.Get("openEHR", "CKM-mirror");
task.Wait();is redudant, the call totask.Resultwould wait implicitly.Here is your method rewritten to use
await.You don't need
.Resulteither as the type ofawaiton aTask<T>isT.On the subject of exception handling you will need to do a
try/catcharound theawait(orResultin your original code). As that is when the exception will be rethrown. Note that this is only true if the exception is thrown in theTask, in theory theGetfunction itself could throw which would have to be caught there.Also note that since you are returning an
asyncyou can choose to catch the exception wherever youawait(orResult) the call.Finally don't forget that if you don't
awaitthe result ofDummyTaskyour task may not complete (orResult).