JIT-отладка в Visual Studio Just-In-Time Debugging in Visual Studio
Эта статья относится к Visual Studio 2015. This article applies to Visual Studio 2015. Если вы ищете последние версии документации Visual Studio, используйте средство выбора версии в верхнем левом углу. If you’re looking for the latest Visual Studio documentation, use the version selector at the top left. Мы рекомендуем выполнить обновление до Visual Studio 2019. We recommend upgrading to Visual Studio 2019. Скачать эту версию можно здесь Download it here
JIT-отладка запускает Visual Studio автоматически при возникновении исключения или сбоя в приложении, работающем за пределами Visual Studio. Just-In-Time debugging launches Visual Studio automatically when an exception or crash occurs in an application that is running outside Visual Studio. Это позволяет протестировать приложение, когда Visual Studio не выполняется, и начать отладку с помощью Visual Studio при возникновении проблемы. This enables you to test your application when Visual Studio is not running, and begin debugging with Visual Studio when a problem occurs.
JIT-отладка работает для классических приложений Windows. Just-In-Time debugging works for Windows desktop apps. Он не работает для универсальных приложений Windows и не работает для управляемого кода, размещенного в собственном приложении, например в визуализаторах. It does not work for Windows Universal apps, and it does not work for managed code that is hosted in a native application, such as Visualizers.
Появляется ли диалоговое окно JIT-отладчик при попытке запустить приложение? Did the Just-in-Time debugger dialog box appear when trying to run an app?
Действия, которые необходимо выполнить при появлении диалогового окна JIT-отладчик Visual Studio, зависят от того, что вы пытаетесь сделать. The actions you should take when you see the Visual Studio Just-in-Time debugger dialog box depend on what you are trying to do:
Если вы хотите избавиться от диалогового окна и просто запустить приложение обычным образом If you want to get rid of the dialog box and just run the app normally
(Опытные пользователи) Если у вас установлен Visual Studio (или он был установлен ранее и удалил его), Отключите JIT-отладку и попробуйте запустить приложение еще раз. (Advanced users) If you have Visual Studio installed (or you had it installed previously and removed it), disable Just-in-Time debugging and try to run the app again.
Если веб-приложение выполняется в Internet Explorer, отключите отладку скриптов. If you are running a web app in Internet Explorer, disable script debugging.
Отключить отладку скриптов в диалоговом окне «Свойства обозревателя». Disable script debugging in the Internet Options dialog box. Доступ к этому средству можно получить из окна свойств сети и Интернета на панели управления / Network and Internet / Internet Options (конкретные действия зависят от используемой версии Windows и Internet Explorer). You can access this from the Control Panel / Network and Internet / Internet Options (the exact steps depend on your version of Windows and Internet Explorer).
Повторно откройте веб-страницу, где была обнаружена ошибка. Re-open the web page where you found the error. Если проблема не устранена, обратитесь к владельцу веб-приложения, чтобы устранить проблему. If this does not resolve the issue, contact the owner of the web app to fix the issue.
Если вы используете другой тип приложения Windows, необходимо обратиться к владельцу приложения, чтобы исправить ошибку, а затем переустановить исправленную версию приложения. If you are running another type of Windows app, you will need to contact the owner of the app to fix the error, and then re-install the fixed version of the app.
Если вы хотите исправить или отладить ошибку (опытных пользователей) If you want to fix or debug the error (advanced users)
- Необходимо установить Visual Studio , чтобы просмотреть подробные сведения об ошибке и попытаться отладить ее. You must have Visual Studio installed to view the detailed information about the error and to try to debug it. Подробные инструкции см. в разделе Использование JIT . See Using JIT for detailed instructions. Если вы не можете устранить ошибку и исправить приложение, обратитесь к владельцу приложения, чтобы устранить ошибку. If you cannot resolve the error and fix the app, contact the owner of the app to resolve the error.
Включение или отключение JIT-отладки Enable or disable Just-In-Time debugging
Вы можете включить или отключить JIT-отладку в диалоговом окне » Сервис/параметры » Visual Studio. You can enable or disable Just-In-Time debugging from the Visual Studio Tools / Options dialog box.
Включение или отключение JIT–отладки To enable or disable Just-In-Time debugging
Запустите Visual Studio. Open Visual Studio. В меню Сервис выберите команду Параметры. On the Tools menu, click Options.
В диалоговом окне Параметры выберите папку Отладка . In the Options dialog box, select the Debugging folder.
В папке Отладка выберите страницу JIT . In the Debugging folder, select the Just-In-Time page.
В поле включить JIT-отладку этих типов кода выберите или отмените выбор соответствующих типов программ: управляемый, машинныйили Скрипт. In the Enable Just-In-Time debugging of these types of code box, select or clear the relevant program types: Managed, Native, or Script.
Чтобы отключить JIT–отладку, если она была включена, необходимы права администратора. To disable Just-In-Time debugging, once it has been enabled, you must be running with Administrator privileges. Включение JIT–отладки устанавливает раздел реестра. Для его изменения требуются права администратора. Enabling Just-In-Time debugging sets a registry key, and Administrator privileges are required to change that key.
Нажмите кнопку ОК. Click OK.
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-отладку из диалогового окна Параметры Visual Studio. When Visual Studio is not installed, you cannot disable Just-In-Time debugging from the Visual Studio Options dialog box. В таком случае JIT-отладку можно отключить, отредактировав реестр Windows. In that case, you can disable Just-In-Time debugging by editing the Windows registry.
Отключение JIT-отладки путем редактирования реестра To disable Just-In-Time debugging by editing the registry
В меню Пуск выполните поиск и выполните команду regedit.exe On the Start menu, search for and run regedit.exe
В окне редактора реестра перейдите к разделу реестра и удалите следующие записи: In the Registry Editor window, locate and delete the follow registry entries:
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, delete the following registry entries also:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows NT\CurrentVersion\AeDebug\Debugger HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows NT\CurrentVersion\AeDebug\Debugger
Будьте внимательны, чтобы случайно не удалить или не изменить какие-либо другие разделы реестра. Take care not to accidentally delete or change any other registry keys.
Закройте окно Редактор реестра. Close the Registry Editor window.
Если вы пытаетесь отключить JIT-отладку для серверного приложения и эти действия не помогли устранить проблему, отключите отладку на стороне сервера в параметрах приложения IIS и повторите попытку. If you are trying to disable Just-In-Time debugging for a server-side app and these steps don’t resolve the issue, turn off server-side debugging in the IIS application settings and retry.
Включение JIT-отладки для приложений Windows Forms To enable Just-In-Time debugging of a Windows Form
По умолчанию для приложений Windows Forms имеется обработчик исключений верхнего уровня, позволяющий программе продолжать работу, если возможно восстановление после ошибки. By default, Windows Forms applications have a top-level exception handler that allows the program to continue to run if it can recover. Например, если приложение Windows Forms создает необработанное исключение, вы увидите диалоговое окно следующего вида: For example, if your Windows Forms application throws an unhandled exception, you will see a dialog like the following:
Чтобы включить JIT-отладку Windows Forms приложения, необходимо выполнить следующие дополнительные действия: To enable Just-In-Time debugging of a Windows Forms application, you must perform the following additional steps:
Задайте jitDebugging значение true в system.windows.form разделе файла machine.config или .exe.config: Set the jitDebugging value to true in the system.windows.form section of the machine.config or .exe.config file:
Для приложений Windows Form, написанных на языке C++, в файле CONFIG или в коде должен быть задан атрибут DebuggableAttribute . In a C++ Windows Form application, you must also set DebuggableAttribute 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. Однако если требуется отладка неоптимизированного построения выпуска, этот атрибут необходимо задать самостоятельно. If you want to debug a non-optimized release build, however, you must set this yourself. Для этого добавьте следующую строку в файл AssemblyInfo.cpp своего приложения: You can do this by adding the following line to your the AssemblyInfo.cpp file of your application:
Для получения дополнительной информации см. DebuggableAttribute. For more information, see DebuggableAttribute.
Использовать JIT-отладку Use Just-In-Time Debugging
В этом разделе показано, что происходит, когда исполняемый объект создает исключение. This section shows what happens when an executable throws an exception.
Для выполнения инструкций необходимо установить Visual Studio. You must have Visual Studio installed to follow these steps. Если у вас нет Visual Studio, вы можете скачать бесплатный выпуск Visual studio 2015 Community Edition. If you don’t have Visual Studio, you can download the free Visual Studio 2015 Community Edition.
При установке Visual Studio JIT-отладка включается по умолчанию. When you install Visual Studio, Just-In-Time debugging is enabled by default.
В этом разделе мы создадим консольное приложение C# в Visual Studio, которое создает исключение NullReferenceException . For the purposes of this section, we’ll make a C# console app in Visual Studio that throws a NullReferenceException.
В Visual Studio создайте консольное приложение C# (файл/создать, проект, Visual C# или консольное приложение) с именем сровснуллексцептион. 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:
Чтобы эта процедура работала в конфигурации выпуска, необходимо отключить только мой код. In order for this procedure to work in a release configuration, you need to turn off Just My Code. В Visual Studio щелкните Сервис/параметры. In Visual Studio, click Tools / Options. В диалоговом окне Параметры выберите Отладка. In the Options dialog, select Debugging. Снимите флажок включить только мой код. Remove the check from Enable Just My Code.
Выполните сборку решения (в Visual Studio выберите Сборка/Перестроение решения). Build the solution (in Visual Studio, choose Build / Rebuild Solution). Можно выбрать конфигурацию отладки или выпуска. You can choose either the Debug or the Release configuration. Дополнительные сведения о конфигурациях сборки см. в разделе Основные сведения о конфигурациях сборки. For more information about build configurations, see Understanding Build Configurations.
Процесс сборки создает исполняемый ThrowsNullException.exe. The build process creates an executable ThrowsNullException.exe. Его можно найти в папке, в которой был создан проект C#: . ..\сровснуллексцептион\сровснуллексцептион\бин\дебуг или . ..\сровснуллексцептион\сровснуллексцептион\бин\релеасе. You can find it under the folder where you created the C# project: . \ThrowsNullException\ThrowsNullException\bin\Debug or . \ThrowsNullException\ThrowsNullException\bin\Release.
Дважды щелкните ThrowsNullException.exe. Double-click the ThrowsNullException.exe. Вы увидите командное окно следующего вида: You should see a command window like this:
Через несколько секунд появится окно ошибки: After a few seconds, an error window appears:
Не нажимайте кнопку Отмена! Do not click Cancel! Через несколько секунд вы увидите две кнопки: Отладка и закрыть программу. After a few seconds, you should see two buttons, Debug and Close program. Нажмите кнопку Отладка. Click Debug.
Если приложение содержит ненадежный код, появится диалоговое окно с предупреждением системы безопасности. If your application contains untrusted code, a dialog box with a security warning appears. Это диалоговое окно позволяет выбрать, следует ли продолжать отладку или нет. This dialog box enables you to decide whether or not to proceed with debugging. Перед продолжением отладки решите, доверяете ли вы данному коду. Before you continue with debugging, decide whether you trust the code. Этот код написан вами самостоятельно? Did you write the code yourself? Доверяете ли вы автору кода? Do you trust the coder? Если приложение выполняется на удаленном компьютере, узнаете ли вы имя процесса? If the application is running on a remote machine, do you recognize the name of the process? Даже если приложение выполняется на локальном компьютере, это не обязательно означает, что ему можно доверять. Even if the application is running locally, that does not necessarily mean it can be trusted. Рассмотрите возможность запуска вредоносного кода на компьютере. Consider the possibility of malicious code running on your computer. Если вы решили, что код, который вы собираетесь отладить, заслуживает доверия, щелкните Отладка. If you decide that the code you are about to debug is trustworthy, click Debug. В противном случае щелкните не выполнять отладку. Otherwise, click Don’t Debug.
Откроется окно отладчика JIT Visual Studio : The Visual Studio Just-In-Time Debugger window appears:
В разделе возможных отладчиковвы увидите, что выбран новый экземпляр Microsoft Visual Studio 2015 . Under Possible Debuggers, you should see that the New instance of Microsoft Visual Studio 2015 line is selected. Выберите сейчас, если он еще не выбран. If it isn’t selected already, select it now.
В нижней части окна в разделе выполните отладку с помощью выбранного отладчика? нажмите кнопку Да. At the bottom of the window, under Do you want to debug using the selected debugger?, click Yes.
Проект Сровснуллексцептион открывается в новом экземпляре Visual Studio с выполнением остановки в строке, вызывающей исключение: The ThrowsNullException project opens in a new instance of Visual Studio, with execution stopped at the line that throws the exception:
Теперь можно начать отладку. You can start debugging at this point. Если бы это было реальное приложение, необходимо выяснить, почему код создает исключение. If this were a real application, you would need to find out why the code is throwing the exception.
Ошибки JIT-отладки Just-In-Time debugging errors
Если диалоговое окно не отображается при аварийном завершении программы, это может быть вызвано отчеты об ошибках Windows параметрами на компьютере. if you don’t see the dialog when the program crashes, this might due to Windows Error Reporting settings on your computer. Дополнительные сведения см. в разделе . Параметры WER. For more information, see .WER Settings.
Могут отображаться следующие сообщения об ошибках, связанные с JIT–отладкой. You might see the following error messages that are associated with 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.
Эта ошибка возникает при попытке подключиться к процессу, выполняемому от имени другого пользователя. This error occurs when you try to attach to a process running as another user.
Чтобы обойти эту проблему, запустите Visual Studio, откройте диалоговое окно Присоединение к процессу из меню Отладка и найдите процесс, который необходимо отладить, в списке Доступные процессы . To work around this problem, start Visual Studio, open the Attach to Process dialog box from the Debug menu, and find the process you want to debug in the Available Processes list. Если вы не знакомы с именем процесса, просмотрите диалоговое окно отладчика Visual Studio и запишите идентификатор процесса. If you do not know the name of the process, look at the Visual Studio Just-In-Time Debugger dialog and note the process ID. Выберите процесс в списке Доступные процессы и нажмите кнопку присоединить. Select the process in the Available Processes list and click Attach. В диалоговом окне JIT-отладчика Visual Studio нажмите кнопку нет , чтобы закрыть диалоговое окно. In the Visual Studio Just-In-Time Debugger dialog, click No to dismiss the dialog box.
Не удалось запустить отладчик, так как пользователь не вошел в систему. Debugger could not be started because no user is logged on.
Данная ошибка возникает, когда JIT–отладка пытается запустить Visual Studio на компьютере, на котором нет пользователей, вошедших в консоль. This error occurs when Just-In-Time debugging tries to start Visual Studio on a machine where there is no user logged onto the console. Так как пользователи, выполнившие вход, отсутствуют, также отсутствует сеанс пользователя, в котором следовало бы отображать диалоговое окно JIT–отладки. Because no user is logged on, there is no user session to display the Just-In-Time debugging dialog box.
Для решения этой проблемы необходимо войти в компьютер. To fix this problem, log onto the machine.
Класс не зарегистрирован. Class not registered.
Эта ошибка указывает, что отладчик пытался создать класс COM, который не зарегистрирован, вероятно, из–за проблем с установкой. This error indicates that the debugger tried to create a COM class that is not registered, probably due to an installation problem.
Чтобы решить эту проблему, используйте установочный диск для переустановки или восстановления установки Visual Studio. To fix this problem, use the setup disk to reinstall or repair your Visual Studio installation.