以指定的时间间隔定期运行异步方法 [英] Run async method regularly with specified interval

查看:37
本文介绍了以指定的时间间隔定期运行异步方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从 C# Web 应用程序向服务发布一些数据.数据本身是在用户使用应用程序时收集的(一种使用统计数据).我不想在每个用户的请求期间向服务发送数据,我宁愿收集应用程序中的数据,然后在单独的线程中的单个请求中发送所有数据,这不满足用户的请求(我的意思是用户不必等待服务处理请求).为此,我需要一种 JS 的 setInterval 模拟 - 每 X 秒启动该函数以将所有收集的数据刷新到服务中.

I need to publish some data to the service from the C# web application. The data itself is collected when user uses the application (a kind of usage statistics). I don't want to send data to the service during each user's request, I would rather collect the data in the app and send then all the data in a single request in a separate thread, that does not serve the users requests (I mean user does not have to wait for the request to be processed by the service). For this purpose I need a kind of JS's setInterval analog - the launch of the function each X seconds to flush all collected data to the service.

我发现Timer 类提供了一些类似的(Elapsed 事件).但是,这允许只运行该方法一次,但这不是什么大问题.它的主要困难在于它需要签名

I found out that Timer class provides somewhat similar (Elapsed event). However, this allows to run the method only once, but that's not a big issue. The main difficulty with it is that it requires the signature

void MethodName(object e, ElapsedEventArgs args)

虽然我想启动异步方法,但它会调用网络服务(输入参数不重要):

while I would like to launch the async method, that will call the web-service (input parameters are not important):

async Task MethodName(object e, ElapsedEventArgs args)

谁能建议如何解决所描述的任务?任何提示表示赞赏.

Could anyone advise how to solve the described task? Any tips appreciated.

推荐答案

async 等价物是一个 while 循环和 Task.Delay (在内部使用 System.Threading.Timer):

The async equivalent is a while loop with Task.Delay (which internally uses a System.Threading.Timer):

public async Task PeriodicFooAsync(TimeSpan interval, CancellationToken cancellationToken)
{
    while (true)
    {
        await FooAsync();
        await Task.Delay(interval, cancellationToken)
    }
}

传递 CancellationToken 很重要,这样您就可以在需要时停止该操作(例如,当您关闭应用程序时).

It's important to pass a CancellationToken so you can stop that operation when you want (e.g. when you shut down your application).

现在,虽然这通常与 .Net 相关,但在 ASP.Net 中,做任何类型的火灾和忘记都是危险的.有几种解决方案(如 HangFire),其中一些记录在 在 ASP.NET 上开火即忘,作者 Stephen Cleary 其他人在 如何运行ASP.NET 中的后台任务 作者:Scott Hanselman

Now, while this is relevant for .Net in general, in ASP.Net it's dangerous to do any kind of fire and forget. There are several solution for this (like HangFire), some are documented in Fire and Forget on ASP.NET by Stephen Cleary others in How to run Background Tasks in ASP.NET by Scott Hanselman

这篇关于以指定的时间间隔定期运行异步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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