我想让我的程序休眠几秒钟。当我使用thread.sleep(x)时,整个程序都没有响应。根据本文的说法,不负责3秒的-> http://msdn.microsoft.com/en-us/library/hh184840(v=VS.92).aspx应用程序没有通过认证:/ (我必须等待5秒)。
发布于 2011-10-19 03:20:34
你需要重新思考你在暂停时想要做什么。很难说,因为我们没有太多关于你试图通过暂停实现什么的信息,但我将在这里举一个例子来说明如何在不暂停整个应用程序的情况下获得想要的效果(这是你永远不应该做的)。
假设您想要下载文件A,然后等待5秒,然后下载文件B。您可以通过运行如下命令来完成此操作:
var file = downloadFileA();
new Thread((ThreadStart)delegate
{
Thread.Sleep(5000);
downloadFileB();
});此外,最好将实际的下载调用设置为异步的(如果您正在进行下载),以确保您不会感觉到GUI。
或者,您也可以在后台进行这两个下载-线程如下:
new Thread((ThreadStart)delegate
{
var file = downloadFileA();
Thread.Sleep(5000);
downloadFileB();
});发布于 2011-10-19 03:19:43
不要休眠你的应用程序的主线程。相反,只要需要在应用程序的后台线程中等待,就可以执行任何需要执行的操作。
如果您将Thread.Sleep()调用放在应用程序的主线程中,则应用程序将在幕后对UI消息循环无响应,如您所见。这是因为您在处理一条消息(触发等待的UI事件)时阻塞了执行,因此不能处理应用程序的其他消息。
相反,将此代码构建为异步运行。我猜有一些方法包含了大部分繁重的任务,包括睡眠。只要这不是一个事件处理程序(如果是,则重构它),您可以设置第二个线程来运行此方法,并添加一个“回调”方法,该方法在完成时将调用该方法,该方法将使用结果更新UI。这是一个稍微多一点的工作,但它保持应用程序的响应,这通常是一个很好的实践,特别是在多核设备上(甚至手机现在都有双核CPU)。有许多方法可以设置多线程操作。Delegate.BeginInvoke是我的最爱:
public delegate void BackgroundMethod()
public void HandleUITrigger(object sender, EventArgs e)
{
//we'll assume the user does something to trigger this wait.
//set up a BackgroundMethod delegate to do our time-intensive task
BackgroundMethod method = DoHeavyLifting;
//The Delegate.BeginInvoke method schedules the delegate to run on
//a thread from the CLR's ThreadPool, and handles the callback.
method.BeginInvoke(HeavyLiftingFinished, null);
//The previous method doesn't block the thread; the main thread will move on
//to the next message from the OS, keeping the app responsive.
}
public void DoHeavyLifting()
{
//Do something incredibly time-intensive
Thread.Sleep(5000);
//Notice we don't have to know that we're being run in another thread,
//EXCEPT this method cannot update the UI directly; to update the UI
//we must call Control.Invoke() or call a method that Invokes itself
ThreadSafeUIUpdate();
}
public void ThreadSafeUIUpdate()
{
//A simple, thread-safe way to make sure that "cross-threading" the UI
//does not occur. The method re-invokes itself on the main thread if necessary
if(InvokeRequired)
{
this.Invoke((MethodInvoker)ThreadSafeUIUpdate);
return;
}
//Do all your UI updating here.
}
public void HeavyLiftingFinished()
{
//This method is called on the main thread when the thread that ran
//DoHeavyLifting is finished. You can call EndInvoke here to get
//any return values, and/or clean up afterward.
}发布于 2011-10-19 03:30:43
免责声明:Thread.Sleep(n) anywhere在很大程度上是一种“代码气味”,这意味着这是一个迹象,表明应用程序中的其他代码也将成为问题。我通常完全避免使用它(我从来没有遇到过必须使用Thread.Sleep的场景)。
然而,在您的例子中,Thread.Sleep(5000)的简单替代方法可能是这样做:
for (int i = 0; i < 10; i++) {
Thread.Sleep(500);
}您将获得5秒的总体等待时间,但UI锁定时间永远不会超过半秒。
https://stackoverflow.com/questions/7812435
复制相似问题