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

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

问题描述

我需要将一些数据从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)

当我想启动异步方法时,它将调用Web服务(输入参数并不重要):

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等效项是带有Task.Delaywhile循环(内部使用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),其中一些解决方案记录在如何运行Scott Hanselman的ASP.NET中的后台任务

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天全站免登陆