Nếu bạn muốn giữ lại các ứng dụng mở ra, bạn không thể làm gì mà giữ quá trình sống, vì vậy nhìn vào mã bên dưới:
while (true);
Đây là cách đơn giản nhất để đạt được hành vi mong đợi, nhưng nó làm rò rỉ CPU, do đó buộc phải lặp lại vô hạn.
Tại thời điểm này, bạn có thể chọn để sử dụng System.Windows.Forms.Application
(nhưng nó đòi hỏi thêm System.Windows.Forms
tham khảo):
Application.Run();
này không rò rỉ CPU và làm việc thành công.
Để tránh thêm System.Windows.Forms
tham khảo bạn có thể sử dụng một thủ thuật đơn giản, nhập khẩu System.Threading
:
SpinWait.SpinUntil(() => false);
này cũng hoạt động hoàn hảo, và nó tinh thần bao gồm trong một iterator while
với một điều kiện phủ nhận đó là được trả về bởi các lambda trên phương pháp. Nhưng nó không rò rỉ CPU! Tại sao? Bạn có thể nhìn vào mã nguồn here, nhưng về cơ bản, spin đang chờ chủ đề hiện tại.
Bạn cũng có thể chọn để tạo một looper thông điệp rằng peeks các thư đang chờ xử và xử lý mỗi trong số họ trước khi chuyển cho phiên bản kế tiếp:
[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;
}
Sau đó, bạn có thể lặp một cách an toàn bằng cách làm một cái gì đó như thế này:
while (true)
ProcessMessageOnce();
Bạn cũng có thể làm điều này tốt hơn bằng cách thay thế while
iterator với một invocation SpinWait.SpinUntil
:
SpinWait.SpinUntil(ProcessMessageOnce);
Bạn có thể thử mở bằng bảng điều khiển. Kéo và thả nó trên giao diện điều khiển và nhấn "Enter". Tôi giả sử một tập tin EXE của nó. –