簡體   English   中英

為什么我的 Thread.Sleep 會導致應用程序崩潰?

[英]Why does my Thread.Sleep causes the app to crash?

我正在制作一個使用 C# 庫的 C++ Winforms 應用程序。 我發現我的應用程序恰好在我的代碼到達 C# 庫中的 Thread.Sleep 時崩潰。 這是 C# 庫中的代碼:

IAsyncResult result = SomeProcessHereEvent?.BeginInvoke(xmlForEQ, null, null);

//System.Threading.Thread.Sleep(250); //putting thread.sleep here will cause the app to crash here, confirming the cause

DateTime dtStart = DateTime.Now;
while (!result.IsCompleted)
{
    System.Threading.Thread.Sleep(200); //this causes the app to crash
}

string xmlReply = string.Empty;
if (result.IsCompleted)
{
    xmlReply = SomeProcessHereEvent.EndInvoke(result);
}

當應用程序崩潰時,我收到的錯誤消息在我的 C++ 應用程序中,這里: 在此處輸入圖像描述

我如何着手更接近解決這個問題?

如果您在 MainThread 即 UI 線程上調用 Thread.sleep(),它將凍結 UI 並導致線程在給定的時間內肯定停止執行; 因此,如果沒有其他線程需要運行,CPU 將進入空閑模式。

為什么不推薦 thread.sleep()? 實現同步的一種方式,實現等待是通過調用Thread。 sleep() function 但是,不建議這樣做,因為這不是很穩定且不可靠。 時間必須以毫秒為單位。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM