如何使应用程序等待并使其他进程在C#中同时运行?

时间:2022-12-10 20:54:27

Using System.Threading.Thread.Sleep( ) makes the entire application stop for the time taken in the arguments. I want other processes running while one process is waiting for a particular amount of time. To put it in short, I want another way other than System.Threading.Thread.Sleep( ) in my application that does not stop the entire thing.

使用System.Threading.Thread.Sleep()使整个应用程序停止在参数中花费的时间。我希望在一个进程等待特定时间的情况下运行其他进程。简而言之,我想在我的应用程序中使用除了System.Threading.Thread.Sleep()之外的另一种方法,它不会停止整个事情。

Example: If I have a label that changes text every 5 seconds, I should be able to press a button which can do some other process, like changing an image.

示例:如果我有一个标签每5秒更改一次文本,我应该可以按一个可以执行其他操作的按钮,例如更改图像。

2 个解决方案

#1


Thread.Sleep() only puts the current thread to sleep. If it is the UI thread, this might block your application and it looks like it is completely blocked. Background threads are still running.

Thread.Sleep()只将当前线程置于休眠状态。如果它是UI线程,这可能会阻止您的应用程序,它看起来完全被阻止。后台线程仍在运行。

If you want to sleep without blocking, you could use the following code:

如果您想要无阻塞地休眠,可以使用以下代码:

await Task.Delay(5000);
// continue here with your code, such as updating your label

This doesn't block the UI thread, just delays the proceeding of your function. You have to declare your method as async

这不会阻止UI线程,只会延迟函数的进程。您必须将方法声明为异步

#2


I am not too informed about this so I am not sure this is the best way to do it

我不太了解这一点,所以我不确定这是最好的方法

The Task.Wait Method

Task.Wait方法

like that your main thread waits for the child thread to complete before continuing. From here on to your problem I guess just brains will help

就像你的主线程在继续之前等待子线程完成一样。从这里到你的问题,我想只是大脑会有所帮助

an other helpful link:

另一个有用的链接:

Thread Synchronization

#1


Thread.Sleep() only puts the current thread to sleep. If it is the UI thread, this might block your application and it looks like it is completely blocked. Background threads are still running.

Thread.Sleep()只将当前线程置于休眠状态。如果它是UI线程,这可能会阻止您的应用程序,它看起来完全被阻止。后台线程仍在运行。

If you want to sleep without blocking, you could use the following code:

如果您想要无阻塞地休眠,可以使用以下代码:

await Task.Delay(5000);
// continue here with your code, such as updating your label

This doesn't block the UI thread, just delays the proceeding of your function. You have to declare your method as async

这不会阻止UI线程,只会延迟函数的进程。您必须将方法声明为异步

#2


I am not too informed about this so I am not sure this is the best way to do it

我不太了解这一点,所以我不确定这是最好的方法

The Task.Wait Method

Task.Wait方法

like that your main thread waits for the child thread to complete before continuing. From here on to your problem I guess just brains will help

就像你的主线程在继续之前等待子线程完成一样。从这里到你的问题,我想只是大脑会有所帮助

an other helpful link:

另一个有用的链接:

Thread Synchronization