长时间的查询.NET线程解决方案长时间、线程、解决方案、NET

2023-09-04 06:34:44 作者:多啦只是个梦

Senerio

我们有一个C#.NET Web应用程序,它记录的事件。外部数据库时,需要一个事件是经主管来进行查询。该查询这个外部数据库有时会采取一段时间来运行。这种滞后通过浏览器体验。

We have a C# .Net Web Application that records incidents. An external database needs to be queried when an incident is approved by a supervisor. The queries to this external database are sometimes taking a while to run. This lag is experienced through the browser.

可能的解决方法

我想用线程来消除模拟挂到浏览器。我已经使用了上课前,并听取了有关线程池。不过,我刚刚找到的BackgroundWorker 的this帖子。

I want to use threading to eliminate the simulated hang to the browser. I have used the Thread class before and heard about ThreadPool. But, I just found BackgroundWorker in this post.

MSDN状态的:

BackgroundWorker的类允许你在一个单独的专用线程中执行的操作。喜欢下载和数据库事务费时的操作可能会导致你的用户界面(UI),以看起来好像它已经停止了,而他们正在运行响应。当你想要一个负责任的UI,你都面临着这样的操作相关的长时间延误,BackgroundWorker的类提供了一个方便的解决方案。

The BackgroundWorker class allows you to run an operation on a separate, dedicated thread. Time-consuming operations like downloads and database transactions can cause your user interface (UI) to seem as though it has stopped responding while they are running. When you want a responsive UI and you are faced with long delays associated with such operations, the BackgroundWorker class provides a convenient solution.

的BackgroundWorker 的方式处理长时间运行的查询时去了?

Is BackgroundWorker the way to go when handling long running queries?

当2个或多个的BackgroundWorker 进程同时运行,会发生什么?是不是像一个池处理?

What happens when 2 or more BackgroundWorker processes are ran simultaneously? Is it handled like a pool?

推荐答案

是的BackgroundWorker 可以显著简化您的线程$ C $下长期运行的操作。关键是对注册在 DoWork的 ProgressChanged 和的 RunWorkerCompleted 事件。这些帮助您避免在有一堆来回传递与线程同步对象,试图以确定操作的进度。

Yes, BackgroundWorker can significantly simplify your threading code for long-running operations. The key is registering for the DoWork, ProgressChanged, and RunWorkerCompleted events. These help you avoid having to have a bunch of synchronization objects passed back and forth with the thread to try to determine the progress of the operation.

另外,我认为进度的事件​​被称为UI线程上,避免了需要调用的 Control.Invoke 以更新的用户界面。

Also, I believe the progress events are called on the UI thread, avoiding the need for calls to Control.Invoke to update your UI.

要回答你的最后一个问题,是的,线程从.NET线程池分配的,因此你,而你可以实例尽可能多的BackgroundWorker的对象,只要你愿意,你可以只运行尽可能多的并发操作的线程池允许。

To answer your last question, yes, threads are allocated from the .NET thread pool, so you while you may instantiate as many BackgroundWorker objects as you'd like, you can only run as many concurrent operations as the thread pool will allow.