I just want a sanity check on this, because I have little experience writing asynchronous functions.
I am subclassing an abstract class and need to override a function with the following signature:
public abstract Task WriteResponseBodyAsync(OutputFormatterWriteContext context);
The function must return task, and my override does not use any asynchronous functions, so to return Task I use Task.Run. Is this the correct usage?
public class FhirJsonFormatter : TextOutputFormatter
{
public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
{
Hl7.Fhir.Serialization.FhirJsonSerializer ser = new Hl7.Fhir.Serialization.FhirJsonSerializer();
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(context.HttpContext.Response.Body))
{
using (Newtonsoft.Json.JsonWriter jw= new Newtonsoft.Json.JsonTextWriter(sw))
{
return Task.Run(() => { ser.Serialize((Hl7.Fhir.Model.Base)context.Object, jw); });
}
}
}
}
Task.CompletedTaskif you have no return value besidesTaskTask.Run; this has overhead that may be detrimental. The caller may actually not want the task to run in a new thread. Make your code not break if the caller wants to call it inside a new thread, but let the caller make that decision.FhirJsonSerializercode that you control? If so maybe think about adding async methods to it. It's best to do async code all the way from the top to the bottom rather than wrapping inTask.Runor just throwing out aTask.CompletedTask, if possible.