这种“忘却"方法正确吗? [英] Is this fire and forget approach correct?

查看:76
本文介绍了这种“忘却"方法正确吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经实现了 instagram api实时更新.基本上,当基于我的订阅添加新图像时,它们会向我提供的URL发出POST请求.

I've implemented instagram api realtime updates. Basically they fire a POST request to a url I provide when there are new images added based on my subscription.

他们说:

"您应该在2秒钟的超时时间内确认POST,如果您需要对接收到的信息进行更多处理,则可以在异步任务中进行."

" you should acknowledge the POST within a 2 second timeout--if you need to do more processing of the received information, you can do so in an asynchronous task."

所以我建立了类似的东西:

so I built something like:

    [HttpPost]
    [ActionName("realtime")]
    public async Task<ActionResult> IndexPost()
    {
        var form = Request.Form;

        Request.InputStream.Position = 0;
        System.IO.StreamReader str = new System.IO.StreamReader(Request.InputStream);
        string sBuf = str.ReadToEnd();

        // deserialize this from json
        var serializer = new JavaScriptSerializer();

        var updates = serializer.Deserialize<IEnumerable<RealtimeUpdate>>(sBuf).ToList();

        ProcessNewTaggedImages(updates);
        return new ContentResult { Content = "Ok" };

    }

其中 ProcessNewTaggedImages 正在异步运行.

 public async void ProcessNewTaggedImages(List<RealtimeUpdate> updates)
        {
            Task.Run(() =>
            {
               // query Instagram api for new images
            }
        }

因此,基本上,当Instagram发布到www.mysite.com/realtime时,它不会等待 ProcessNewTaggedImages .

so basically when Instagram POSTs to www.mysite.com/realtime it does not wait for ProcessNewTaggedImages.

我只是想确保这种方法正确无误,因为在Task.Run下,我会收到一条警告:

I just wanted to make sure this approach is correct for fire and forget approach because under Task.Run I receive a warning saying:

由于不等待此调用,因此在调用完成之前将继续执行当前方法.考虑将await运算符应用于调用结果.

Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the await operator to the result of the call.

但是我不想在这里等待,因为

but I don't want await here because

  1. 我的处理结果与instagram通话无关紧要
  2. POST的超时时间为2秒,所以我不想等待此处理.

您能确认我在正确的轨道上吗?Ps:POST运作良好,并且一切正常,只是想确认我没有做任何错事,因为我主要是C#中这种异步方法的初学者.

Can you confirm I am on the right track? Ps: POST is working fine and all works good just wanted to confirm I've not done any mystake because I am mostly beginner to this async approach in C#.

推荐答案

如果您需要即弃功能,则无需在方法中添加异步关键字,因为您没有等待任何操作.因此,从代码中删除异步关键字,编译器将不会抱怨您的代码.

If you need fire and forget functionality you don't need to add async keywords to your methods as your are not doing any awaits. So remove the async keywords from your code and the compiler will not complain about your code.

这篇关于这种“忘却"方法正确吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆