简体   繁体   English

使用Task.Run写一个异步方法

[英]Using Task.Run to write an asynchronous method

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.该函数必须返回任务,而我的重写不使用任何异步函数,因此要返回任务,我使用 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.Run will run the code on another thread, which is probably not what you want. Task.Run将在另一个线程上运行代码,这可能不是您想要的。

Why not just return Task.CompletedTask :为什么不直接返回Task.CompletedTask

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))
        {
            ser.Serialize((Hl7.Fhir.Model.Base)context.Object, jw);
        }
    }
    return Task.CompletedTask;
}

Also with your example, the method may return before ser.Serialize has finished, causing jw , sw and maybe even context to be disposed.同样对于您的示例,该方法可能会在ser.Serialize完成之前返回,从而导致jwsw甚至context被释放。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM