为什么Visual Studio在此语句之后退出调试模式

本文关键字:之后 退出 调试 模式 语句 Visual Studio 为什么 | 更新日期: 2023-09-27 18:17:31

我正在尝试调试一些异步代码,当我尝试在调试器中单步执行代码行时,一切都很好,直到它到达下面代码片段中的第 18 行。 运行该行后,调试器将停止,VS 退出调试模式。是否有一种特定的方法来调试我缺少的异步程序,或者代码中是否有不正确的内容?

1. private static void ReadAsynchronously(IAsyncResult ar)
2.        {
3.            StateObject state = (StateObject)ar.AsyncState;
4.            //Data buffer for incoming data
5.            byte[] bytes = new byte[1024];
6.
7.            Socket readHandler = state.workSocket;
8.            
9.            //Flag variable for identifying the End of Character from the read message
10.            bool pFlag = false;
11.
12.            //String variable for store the reading data from the client socket 
13.            string content = string.Empty;
14.            string data = string.Empty;
15.
16.
17.            // Read data from the client socket.
18.            int read = readHandler.EndReceive(ar);
19.
20.            if (read > 0)
21.            {
                   ........

为什么Visual Studio在此语句之后退出调试模式

您可能在 EndRead 调用中缺少异常,请尝试使用 catch 块并检查:

int read;
try
{
    read = readHandler.EndReceive(ar);
}
catch (Exception ex)
{
    System.Diagnostics.Debug.WriteLine(ex.ToString()); //ADD BREAKPOINT HERE
}

每次单步执行一行代码时,调试器都会让该行代码运行,然后返回到中断状态。在第 18 行中,正在发生的事情是代码行需要很长时间才能运行,因此调试器似乎已停止调试,但尚未停止:如果该行代码最终完成,调试器将中断。

您将需要调查该操作未完成的原因或为什么需要这么长时间。EndReceive 方法将阻塞,直到数据可用,因此最可能的原因是连接另一端的进程实际上没有发送任何数据。

编辑:如果执行发送的代码是您自己的,并且您使用的是StreamWriter请确保在写入后调用Flush()。或者,可以通过 AutoFlush 属性打开自动刷新。