gpt4 book ai didi

c# - 线程 sleep 在 Windows Phone 7 上运行不佳

转载 作者:行者123 更新时间:2023-11-30 18:57:19 25 4
gpt4 key购买 nike

我想让我的程序休眠几秒钟。当我使用 thread.sleep(x) 时,整个程序没有响应。根据这篇文章 -> http://msdn.microsoft.com/en-us/library/hh184840(v=VS.92).aspx不负责3秒的应用不通过认证:/(我要等5秒)。

最佳答案

不要让应用程序的主线程休眠。相反,做任何需要在应用程序的后台线程中等待的事情。

如果您在应用程序的主线程中调用 Thread.Sleep(),应用程序将无法响应幕后的 UI 消息循环,如您所见。这是因为您在处理一条消息(触发等待的 UI 事件)时阻止了执行,因此无法处理该应用的其他消息。

相反,构建此代码以异步运行。我猜想有一些方法包含大部分繁重的工作,包括 sleep 。只要它不是事件处理程序(如果是,就重构它),你可以设置第二个线程来运行这个方法,并添加一个“回调”方法,该方法将在它完成时调用,这将更新 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.
}

关于c# - 线程 sleep 在 Windows Phone 7 上运行不佳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7812435/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com