简体   繁体   English

为什么我的 Thread.Sleep 会导致应用程序崩溃?

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

I'm making a C++ Winforms Application that consumes a C# Library.我正在制作一个使用 C# 库的 C++ Winforms 应用程序。 I found that my application crashes exactly at the point where my code reaches Thread.Sleep in my C# library.我发现我的应用程序恰好在我的代码到达 C# 库中的 Thread.Sleep 时崩溃。 Here is the code in the C# library:这是 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);
}

When the app crashes, the error message that I got is in my C++ app, here:当应用程序崩溃时,我收到的错误消息在我的 C++ 应用程序中,这里: 在此处输入图像描述

How do I proceed to get closer to solving this problem?我如何着手更接近解决这个问题?

If you are calling Thread.sleep() on MainThread ie UI thread, It will freeze the UI and causes the thread to definitely stop executing for a given amount of time;如果您在 MainThread 即 UI 线程上调用 Thread.sleep(),它将冻结 UI 并导致线程在给定的时间内肯定停止执行; So if there is no other thread needs to be run, CPU will goes in Idle mode.因此,如果没有其他线程需要运行,CPU 将进入空闲模式。

Why is thread.sleep() not recommended?为什么不推荐 thread.sleep()? One of the way to achieve synchronization, implement wait is by calling Thread.实现同步的一种方式,实现等待是通过调用Thread。 sleep() function however, it is not recommended because this is not very stable and unreliable. sleep() function 但是,不建议这样做,因为这不是很稳定且不可靠。 The time has to be specified in milliseconds.时间必须以毫秒为单位。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM