asp.net 在长时间运行的任务上向用户输出消息
在 ASP.NET 的长时间进程中向用户发送消息的最佳方式是什么?在其他语言中,有一个刷新方法,我看到asp.net也有这个方法,但这是最好的方法吗?如果不是,你还能怎么做?
What is the best way to send messages to the user during a long process in asp.net. In other languages there is a flush method and I see that asp.net has that as well but is that the best way? If not, how else can you do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
最好的方法是生成一个单独的线程来执行长时间运行的进程,然后在主线程上进行 ajax 调用,从长时间运行的线程请求状态并根据需要显示状态。
可以在这里找到一篇相对较好的文章,深入解释了这一点: http://www.devarchive.net/displaying_progress_bar_for_long_running_processes .aspx
The best way to do it is to spawn a separate thread that performs the long running process and then have an ajax call on the main thread that requests status from the long running thread and displays the status as appropriate.
A relatively good article that explains this in depth can be found here: http://www.devarchive.net/displaying_progress_bar_for_long_running_processes.aspx
使用推送通知框架 (comet) http://pokein.codeplex.com/ 或将您的状态保存到数据库和您的页面要么刷新以获取状态,要么使用 jQuery.ajax() 获取数据,或者刷新计时器上的 UpdatePanel,例如: http://msdn.microsoft.com/en-us/library/cc295400.aspx
不管怎样 - 你的“进度”需要保存到当前会话或数据库并读取。 UI 通常不会直接与处理线程交互,但两者都会与某些包含更新状态的中间介质进行通信。
Either use a push notification framework (comet) http://pokein.codeplex.com/ or save your status to a database and your page either refreshes to get the status or uses jQuery.ajax() for example to get the data back or refreshes an UpdatePanel on a timer such as: http://msdn.microsoft.com/en-us/library/cc295400.aspx
Either way though - your 'progress' needs to be saved to either the current session or to a database and read. The UI generally wouldn't interact directly with the processing thread, but both talk to some intermediate medium that contains the update status.
正如 Adam Tuliper 所说,您需要一个推送通知框架,最好的选择是 Microsoft 的 SignalR。无需在任何地方存储状态,或实施轮询。 SignalR 会将您需要的所有内容推送回浏览器,而启动进程的请求(在不同的线程上)则通过 HubContext 类将其消息直接发送到客户端。详细信息可以在此处找到。
As Adam Tuliper said -- you need a push notification framework, and the best choice would be SignalR from Microsoft. No need to store the status anywhere, or implement polling. SignalR will push everything you need back to the browser, while the request that started the process (on a different thread) sends its messages directly to the client via the HubContext class. The details can be found here.