如果你想继续公开你的申请,你必须做一些事情,以便保持工作活力。 下面的例子最简单,将在您的方案结束时:
while (true) ;
然而,它造成邮联超负荷工作,因为它因此被迫无限期地燃烧。
此时,您可选择使用<条码>System. .Forms.Application类别(但要求您添加<条码>System.Windows.Forms参考资料):
Application.Run();
This doesn t leak CPU and works successfully.
In order to avoid to add System.Windows.Forms
reference, you can use a simple trick, the so-called spin waiting, importing System.Threading
:
SpinWait.SpinUntil(() => false);
这也完美无缺,基本上由while
的路段构成,其背后的条件由上述“lambda”方法归还。 为什么这种超载荷是这样? 查阅来源代码here;任何方面,它基本上等到万国邮联的某些周期再接手。
您还可以创建信息传承器,在发送到下台之前,将系统和程序的未决信息推向下台:
[DebuggerHidden, DebuggerStepperBoundary, DebuggerNonUserCode, DllImport("user32.dll", EntryPoint = "PeekMessage")]
public static extern int PeekMessage(out NativeMessage lpMsg, IntPtr hWnd, int wMsgFilterMin, int wMsgFilterMax, int wRemoveMsg);
[DebuggerHidden, DebuggerStepperBoundary, DebuggerNonUserCode, DllImport("user32.dll", EntryPoint = "GetMessage")]
public static extern int GetMessage(out NativeMessage lpMsg, IntPtr hWnd, int wMsgFilterMin, int wMsgFilterMax);
[DebuggerHidden, DebuggerStepperBoundary, DebuggerNonUserCode, DllImport("user32.dll", EntryPoint = "TranslateMessage")]
public static extern int TranslateMessage(ref NativeMessage lpMsg);
[DebuggerHidden, DebuggerStepperBoundary, DebuggerNonUserCode, DllImport("user32.dll", EntryPoint = "DispatchMessage")]
public static extern int DispatchMessage(ref NativeMessage lpMsg);
[DebuggerHidden, DebuggerStepperBoundary, DebuggerNonUserCode]
public static bool ProcessMessageOnce()
{
NativeMessage message = new NativeMessage();
if (!IsMessagePending(out message))
return true;
if (GetMessage(out message, IntPtr.Zero, 0, 0) == -1)
return true;
Message frameworkMessage = new Message()
{
HWnd = message.handle,
LParam = message.lParam,
WParam = message.wParam,
Msg = (int)message.msg
};
if (Application.FilterMessage(ref frameworkMessage))
return true;
TranslateMessage(ref message);
DispatchMessage(ref message);
return false;
}
那么,你可以安全地 lo,做这样的事情:
while (true)
ProcessMessageOnce();