如何让子线程休眠而不冻结 WPF 应用程序中的 UI 线程?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15722400/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 08:23:39  来源:igfitidea点击:

How to make a child thread sleep without freezing UI thread in WPF application?

c#wpfmultithreadingsleepthread-sleep

提问by Rohit Vats

I have a WPF application and I have individual threads running to accomplish tasks and I would like to have the current thread to go to sleep something like,

我有一个 WPF 应用程序,我有单独的线程在运行以完成任务,我想让当前线程进入睡眠状态,例如,

Thread.CurrentThread.Sleep(10000)

Thread.CurrentThread.Sleep(10000)

I do see it in Java but not in C#. I do know that I only have only one UI thread, so if I use Thread.Sleep(10000) my UI thread will be block. I am using async and await from .NET 4.5.

我确实在 Java 中看到它,但在 C# 中没有。我知道我只有一个 UI 线程,所以如果我使用 Thread.Sleep(10000) 我的 UI 线程将被阻塞。我正在使用 .NET 4.5 的异步和等待。

var words = await Task.Factory.StartNew(() => { StringMgr.TextToUniqueWords(File.ReadAllText(filename));

// I want to be able to sleep this thread for 10 seconds, without the UI freezing

});

var words = await Task.Factory.StartNew(() => { StringMgr.TextToUniqueWords(File.ReadAllText(filename));

// 我希望能够让这个线程休眠 10 秒,而不会冻结 UI

});

So how do I put a child thread to sleep without freezing the UI thread in a WPF application?

那么如何在不冻结 WPF 应用程序中的 UI 线程的情况下让子线程进入睡眠状态?

Thanks!

谢谢!

回答by Stephen Cleary

Since you're already using async, you can just do it the asynchronous way:

由于您已经在使用async,您可以以异步方式进行操作:

var words = await Task.Run(async () =>
{
  StringMgr.TextToUniqueWords(File.ReadAllText(filename));
  await Task.Delay(TimeSpan.FromSeconds(10));
});

However, I suspect that sleeping is the wrong solution for the actual problem you're trying to solve. If you'd like to post another question with your actual problem, you may find a better solution.

但是,我怀疑睡眠是您要解决的实际问题的错误解决方案。如果您想就实际问题发布另一个问题,您可能会找到更好的解决方案。

回答by Rohit Vats

Have you tried it? Sleeping thread inside a Task won't freeze your GUIbut it will make the current background thread to go in sleep mode and your UI will remain responsive always -

你试过吗?Sleeping thread inside a Task won't freeze your GUI但它会使当前的后台线程进入睡眠模式,并且您的 UI 将始终保持响应-

        Task.Factory.StartNew(() =>
            {
                Thread.Sleep(5000000); // this line won't make UI freeze.
            });
        Thread.Sleep(5000000); // But this will certainly do.