等待一个漫长的过程,仍然更新UI漫长、过程、UI

2023-09-05 23:27:50 作者:作业是会呼吸的痛

我一直在尝试创建写入到数据库中,而不会阻塞UI线程的任务。我在等待的过程中没有发生阻塞完成的最大的问题。

I've been attempting to create a task that writes to a database without blocking the UI thread. The biggest problem I'm having is waiting for that process to finish without the blocking happening.

我一直在试图避免使用的DoEvents (虽然它的使用相当频繁通过这个节目,现在,我想搬出去使用它,而前进)。

I've been trying to avoid using DoEvents (though it's used quite frequently through this program right now, I'd like to move out of using it while moving forward).

我试图创建要在第二个线程,并等待它完成以及使用运行过程中的的BackgroundWorker

I've attempted to create the process to run on a 2nd thread and waiting for it to finish as well as using a BackgroundWorker.

这个问题我已经跟这个是不是有在不同的线程的code运行,但试图找到一种方法来等待它完成。

The problem I have with this is not having the code run in a different thread, but trying to find a way to wait for it to finish.

基本上,现在我做到以下几点:

Basically, Right now I do the following:

连接到数据库 创建一个后台工作(或线程)来执行写入到数据库(我可能会结束与的BackgroundWorker 这样我就可以使用 ReportProgress 启动线程或的BackgroundWorker 使用whil​​e循环来等待线程/ 的BackgroundWorker 来完成。对于线程,我等待的IsAlive 成为假,因为的BackgroundWorker ,我切换一个布尔变量。 我让用户知道这个过程就完成了。 Connect to the database Create a background worker (or thread) to do the writing to the database (I will probably end up with the BackgroundWorker so I can use the ReportProgress Start the thread or BackgroundWorker Use a While loop to wait for the thread / BackgroundWorker to finish. For the thread, I wait for IsAlive to become false, for the BackgroundWorker, I toggle a boolean variable. I let the user know the process is finished.

现在的问题是在#4。

这样做没有code while循环它,或的Thread.Sleep(0)树叶挡住了UI(主题。睡眠(0)使程序走程序资源的100%为好)

Doing a while loop with no code in it, or a Thread.Sleep(0) leaves the UI blocked (Thread.Sleep(0) makes the program take 100% of the program resources as well)

所以,我做的:

while (!thread.IsAlive)
   Thread.Sleep(1);

- 或 -

-or-

while (bProcessIsRunning)
   Thread.Sleep(1);

以阻止用户界面。

which blocks the UI.

如果我称之为 Application.DoEvents()在那里,用户界面​​更新(虽然它是可以点击的,所以我必须禁用整个形式,而此进程中运行)。

If I call Application.DoEvents() there, the UI is updated (though it's clickable, so I have to disable the entire form while this process runs).

如果我运行过程中同步进行,我还需要创建用户界面进行更新某种方式(在我的脑海中,的DoEvents 通话),所以它不'T出现锁起来。

If I run the process synchronously, I still need to create some sort of way for the UI to be updated (in my mind, a DoEvents call) so it doesn't appear locked up.

我是什么做错了吗?

推荐答案

C#中使用事件模型 - 你想做的事就是调度,做工作的过程,然后有一个过程触发一个自定义事件完成或使用时,一个线程的事件。虽然过程中背景释放控制从code跑回系统。

C# uses an event model -- what you want to do is dispatch the process that does the work and then have that process fire a custom event when done or use one of the threading events. While the process is running in the "background" release control back to the system from your code.

 
精彩推荐