- Отладка с помощью JIT-отладчика в Visual Studio Debug using the Just-In-Time Debugger in Visual Studio
- Включение или отключение JIT-отладки в Visual Studio Enable or disable Just-In-Time debugging in Visual Studio
- Отключение JIT-отладки из реестра Windows Disable Just-In-Time debugging from the Windows registry
- Включение JIT-отладки для приложений Windows Forms Enable Just-In-Time debugging of a Windows Form
- Использование JIT-отладки Use Just-In-Time debugging
- Устранение неполадок с JIT-отладкой Troubleshoot Just-In-Time debugging
Отладка с помощью JIT-отладчика в Visual Studio Debug using the Just-In-Time Debugger in Visual Studio
JIT-отладка автоматически запускает Visual Studio при возникновении ошибок или сбоев в приложении, запущенном вне Visual Studio. Just-In-Time debugging can launch Visual Studio automatically when an app running outside Visual Studio errors or crashes. С помощью JIT-отладки можно тестировать приложения за пределами Visual Studio и открыть Visual Studio, чтобы начать отладку в случае проблемы. With Just-In-Time debugging, you can test apps outside of Visual Studio, and open Visual Studio to begin debugging when a problem occurs.
JIT-отладка работает для классических приложений Windows. Just-In-Time debugging works for Windows desktop apps. Она не работает для универсальных приложений Windows или управляемого кода, размещенного в приложении машинного кода, например для визуализаторов. It does not work for Universal Windows Apps, or for managed code that is hosted in a native application, such as Visualizers.
Если вы просто хотите запретить отображение диалогового окна JIT-отладчика, но у вас не установлена Visual Studio, см. раздел Отключение JIT-отладчика. If you just want to stop the Just-In-Time Debugger dialog box from appearing, but don’t have Visual Studio installed, see Disable the Just-In-Time Debugger. Если набор средств Visual Studio был ранее установлен, но теперь его нет, придется отключить JIT-отладку через реестр Windows. If you once had Visual Studio installed, you may need to disable Just-In-Time debugging from the Windows registry.
Включение или отключение JIT-отладки в Visual Studio Enable or disable Just-In-Time debugging in Visual Studio
Чтобы включить или отключить JIT-отладку, необходимо запустить Visual Studio от имени администратора. To enable or disable Just-In-Time debugging, you must be running Visual Studio as an administrator. Включение или отключение JIT-отладки устанавливает раздел реестра. Для его изменения требуются права администратора. Enabling or disabling Just-In-Time debugging sets a registry key, and administrator privileges may be required to change that key. Откройте Visual Studio с правами администратора, щелкнув приложение Visual Studio правой кнопкой мыши и выбрав Запуск от имени администратора. To open Visual Studio as an administrator, right-click the Visual Studio app and choose Run as administrator.
JIT-отладку можно настроить в диалоговом окне Visual Studio Сервис > Параметры (или Отладка > Параметры). You can configure Just-In-Time debugging from the Visual Studio Tools > Options (or Debug > Options) dialog box.
Включение или отключение JIT–отладки To enable or disable Just-In-Time debugging:
В меню Сервис или Отладка выберите Параметры > Отладка > JIT. On the Tools or Debug menu, select Options > Debugging > Just-In-Time.
В поле Включить JIT-отладку для этих типов кода выберите типы кода, которым требуется JIT-отладка: Управляемый, Собственный и (или) Скрипт. In the Enable Just-In-Time debugging for these types of code box, select the types of code you want Just-In-Time debugging to debug: Managed, Native, and/or Script.
Нажмите кнопку ОК. Select OK.
Если вы включили JIT-отладчик, но он не открывается при сбоях или ошибках приложения, см. раздел Устранение неполадок с JIT-отладкой. If you enable the Just-In-Time debugger, but it doesn’t open when an app crashes or errors, see Troubleshoot Just-In-Time debugging.
Отключение JIT-отладки из реестра Windows Disable Just-In-Time debugging from the Windows registry
JIT-отладка может оставаться включенной даже после удаления Visual Studio с компьютера. Just-In-Time debugging may still be enabled even if Visual Studio is no longer installed on your computer. Если Visual Studio больше не установлена, JIT-отладку можно отключить, отредактировав реестр Windows. If Visual Studio is no longer installed, you can disable Just-In-Time debugging by editing the Windows registry.
Отключение JIT-отладки путем редактирования реестра To disable Just-In-Time debugging by editing the registry:
В меню Windows Пуск запустите редактор реестра (regedit.exe). From the Windows Start menu, run the Registry Editor (regedit.exe).
В окне Редактор реестра найдите и удалите следующие записи реестра. In the Registry Editor window, locate and delete the following registry entries:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\DbgManagedDebugger HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\DbgManagedDebugger
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AeDebug\Debugger HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AeDebug\Debugger
Если на компьютере установлена 64-разрядная операционная система, также удалите следующие записи реестра. If your computer is running a 64-bit operating system, also delete the following registry entries:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\DbgManagedDebugger HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\DbgManagedDebugger
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows NT\CurrentVersion\AeDebug\Debugger HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows NT\CurrentVersion\AeDebug\Debugger
Будьте внимательны, чтобы не удалить или не изменить другие разделы реестра. Make sure not to delete or change any other registry keys.
Закройте окно Редактор реестра. Close the Registry Editor window.
Включение JIT-отладки для приложений Windows Forms Enable Just-In-Time debugging of a Windows Form
По умолчанию в приложениях Windows Forms есть обработчик исключений верхнего уровня, который позволяет приложению продолжить работу, если оно может быть восстановлено. By default, Windows Form apps have a top-level exception handler that lets the app keep running if it can recover. Если приложение Windows Forms выдает необработанное исключение, отображается следующее диалоговое окно: If a Windows Forms app throws an unhandled exception, it shows the following dialog:
Чтобы включить JIT-отладку вместо стандартной обработки ошибок Windows Forms, добавьте следующие параметры. To enable Just-In-Time debugging instead of standard Windows Form error handling, add these settings:
Для приложений Windows Forms, написанных на языке C++, в файле CONFIG или коде также задайте для параметра DebuggableAttribute значение true . In a C++ Windows Form application, also set DebuggableAttribute to true in a .config file or in your code. Если компиляция выполняется с атрибутом /Zi, но без /Og, компилятор автоматически задаст этот атрибут. If you compile with /Zi and without /Og, the compiler sets this attribute for you. Однако если требуется выполнить отладку неоптимизированной сборки выпуска, то необходимо задать DebuggableAttribute , добавив следующую строку в файл AssemblyInfo.cpp приложения: If you want to debug a non-optimized release build, however, you must set DebuggableAttribute by adding the following line in your app’s AssemblyInfo.cpp file:
Для получения дополнительной информации см. DebuggableAttribute. For more information, see DebuggableAttribute.
Использование JIT-отладки Use Just-In-Time debugging
В этом примере рассматривается JIT-отладка, когда приложение выдает ошибку. This example walks you through Just-In-Time debugging when an app throws an error.
Для выполнения инструкций необходимо установить Visual Studio. You must have Visual Studio installed to follow these steps. Если у вас нет Visual Studio, вы можете скачать бесплатный выпуск Visual Studio Community. If you don’t have Visual Studio, you can download the free Visual Studio Community Edition.
Убедитесь, что JIT-отладка включена в разделе Сервис > Параметры > Отладка > JIT. Make sure Just-In-Time debugging is enabled in Tools > Options > Debugging > Just-In-Time.
В этом примере вы создадите консольное приложение C# в Visual Studio, которое создает исключение NullReferenceException. For this example, you’ll make a C# console app in Visual Studio that throws a NullReferenceException.
В Visual Studio создайте консольное приложение C# (Файл > Создать > Проект > Visual C# > Консольное приложение) с именем ThrowsNullException. In Visual Studio, create a C# console app (File > New > Project > Visual C# > Console Application) named ThrowsNullException. Сведения о создании проектов в Visual Studio см. в разделе Пошаговое руководство. Создание простого приложения. For more information about creating projects in Visual Studio, see Walkthrough: Create a simple application.
Когда проект откроется в Visual Studio, откройте файл Program.cs. When the project opens in Visual Studio, open the Program.cs file. Замените метод Main() следующим кодом, который выводит строку на консоль, а затем создает исключение NullReferenceException: Replace the Main() method with the following code, which prints a line to the console and then throws a NullReferenceException:
Чтобы выполнить сборку решения, выберите конфигурацию Отладка (по умолчанию) или Выпуск, а затем нажмите Сборка > Перестроить решение. To build the solution, choose either the Debug (default) or Release configuration, and then select Build > Rebuild Solution.
- Выберите конфигурацию Отладка для полной отладки. Choose Debug configuration for the full debugging experience.
- Если выбрана конфигурация Выпуск, необходимо отключить функцию Только мой код. If you select Release configuration, you must turn off Just My Code for this procedure to work. В разделе Сервис >Параметры >Отладка снимите флажок Включить только мой код. Under Tools >Options >Debugging, deselect Enable Just My Code.
Дополнительные сведения о конфигурациях сборки см. в разделе Общие сведения о конфигурациях сборки. For more information about build configurations, see Understanding build configurations.
Откройте созданное приложение ThrowsNullException.exe в папке проекта C# ( . \ThrowsNullException\ThrowsNullException\bin\Debug или . \ThrowsNullException\ThrowsNullException\bin\Release). Open the built app ThrowsNullException.exe in your C# project folder (. \ThrowsNullException\ThrowsNullException\bin\Debug or . \ThrowsNullException\ThrowsNullException\bin\Release).
Вы увидите следующее окно команд: You should see the following command window:
Откроется диалоговое окно Выбор JIT-отладчика. The Choose Just-In-Time Debugger dialog opens.
В разделе Доступные отладчики выберите параметр Новый экземпляр , если он еще не выбран. Under Available Debuggers, select New instance of , if not already selected.
Нажмите кнопку ОК. Select OK.
Проект ThrowsNullException открывается в новом экземпляре Visual Studio, а выполнение остановлено в строке, вызвавшей исключение: The ThrowsNullException project opens in a new instance of Visual Studio, with execution stopped at the line that threw the exception:
Теперь можно начать отладку. You can start debugging at this point. При отладке реального приложения необходимо выяснить, почему код создает исключение. If you were debugging a real app, you would need to find out why the code is throwing the exception.
Если приложение содержит ненадежный код, появляется диалоговое окно предупреждения системы безопасности, позволяющее решить, следует ли продолжить отладку. If your app contains untrusted code, a security warning dialog box appears, enabling you to decide whether to proceed with debugging. Перед продолжением отладки решите, доверяете ли вы данному коду. Before you continue debugging, decide whether you trust the code. Этот код написан вами самостоятельно? Did you write the code yourself? Если приложение выполняется на удаленном компьютере, узнаете ли вы имя процесса? If the application is running on a remote machine, do you recognize the name of the process? Если приложение выполняется локально, учитывайте возможность выполнения такого вредоносного кода на вашем компьютере. If the app is running locally, consider the possibility of malicious code running on your computer. Если вы решили, что код заслуживает доверия, нажмите ОК. If you decide the code is trustworthy, select OK. В противном случае нажмите кнопку Отмена. Otherwise, select Cancel.
Устранение неполадок с JIT-отладкой Troubleshoot Just-In-Time debugging
Если JIT-отладка не запускается при сбое приложения, даже если она включена в Visual Studio: If Just-In-Time debugging doesn’t start when an app crashes, even though it is enabled in Visual Studio:
Отчеты об ошибках Windows могут взять на себя обработку ошибок на компьютере. Windows Error Reporting could be taking over the error handling on your computer.
Чтобы устранить эту проблему, используйте редактор реестра, чтобы добавить значение DWORD Отключено с параметром Данные значения, равным 1, для следующих разделов реестра: To fix this issue, use Registry Editor to add a DWORD Value of Disabled, with Value data of 1, to the following registry keys:
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\Windows Error Reporting HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\Windows Error Reporting
(Для 64-разрядных компьютеров): HKEY_LOCAL_MACHINE\Software\WOW6432Node\Microsoft\Windows\Windows Error Reporting (For 64-bit machines): HKEY_LOCAL_MACHINE\Software\WOW6432Node\Microsoft\Windows\Windows Error Reporting
Дополнительные сведения см. в разделе Параметры .WER. For more information, see .WER settings.
Известная проблема Windows может привести к сбою JIT-отладчика. A known Windows issue may be causing the Just-In-Time debugger to fail.
Исправление состоит в том, чтобы добавить значение DWORD из раздела Видимые с параметром Значение данных, равным 1, в следующие разделы реестра. The fix is to add a DWORD Value of Auto, with Value data of 1, to the following registry keys:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AeDebug HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AeDebug
(Для 64-разрядных компьютеров): HKEY_LOCAL_MACHINE\Software\WOW6432Node\Microsoft\Windows NT\CurrentVersion\AeDebug (For 64-bit machines): HKEY_LOCAL_MACHINE\Software\WOW6432Node\Microsoft\Windows NT\CurrentVersion\AeDebug
Во время JIT-отладки могут отображаться следующие сообщения об ошибках. You might see the following error messages during Just-In-Time debugging:
Не удалось подключиться к аварийному процессу. Указанная программа не является программой Windows или MS–DOS. Unable to attach to the crashing process. The specified program is not a Windows or MS-DOS program.
Отладчик попытался подключиться к процессу, выполняющемуся под именем другого пользователя. The debugger tried to attach to a process running under another user.
Чтобы обойти эту проблему, запустите Visual Studio, откройте диалоговое окно Отладка > Присоединение к процессу и найдите процесс, для которого требуется выполнить отладку, в списке Доступные процессы. To work around this problem, in Visual Studio, open Debug > Attach to Process, and find the process you want to debug in the Available Processes list. Если имя процесса неизвестно, найдите идентификатор процесса в диалоговом окне JIT-отладчик Visual Studio. If you do not know the name of the process, find the Process ID in the Visual Studio Just-In-Time Debugger dialog. Выберите процесс в списке Доступные процессы и щелкните Присоединить. Select the process in the Available Processes list, and select Attach. Выберите Нет, чтобы закрыть диалоговое окно JIT-отладчика. Select No to dismiss the Just-In-Time debugger dialog.
Не удалось запустить отладчик, так как пользователь не вошел в систему. Debugger could not be started because no user is logged on.
В консоли нет пользователей, выполнивших вход, а также отсутствует сеанс пользователя, в котором следовало бы отображать диалоговое окно JIT-отладки. There is no user logged onto the console, so there is no user session to display the Just-In-Time debugging dialog.
Для решения этой проблемы необходимо войти в компьютер. To fix this problem, log onto the machine.
Класс не зарегистрирован. Class not registered.
Отладчик пытался создать класс COM, который не зарегистрирован, вероятно, из-за проблем с установкой. The debugger tried to create a COM class that is not registered, probably due to an installation problem.
Чтобы решить эту проблему, используйте Visual Studio Installer для переустановки или исправления установки Visual Studio. To fix this problem, use the Visual Studio Installer to reinstall or repair your Visual Studio installation.