以指定的时间间隔定期运行异步方法

编程入门 行业动态 更新时间:2024-10-27 18:29:58
本文介绍了以指定的时间间隔定期运行异步方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要从 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

更多推荐

以指定的时间间隔定期运行异步方法

本文发布于:2023-10-16 11:29:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1497429.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:间隔   时间   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!