문제

Windows Service Control Manager를 통해 서비스를 시작한 다음 디버거를 스레드에 첨부하는 것보다 코드를 밟는 더 쉬운 방법이 있습니까? 그것은 번거롭고 더 간단한 접근 방식이 있는지 궁금합니다.

도움이 되었습니까?

해결책

서비스를 신속하게 디버깅하고 싶다면 Debugger.Break() 거기에. 그 줄에 도달하면, 그것은 나를 V로 다시 떨어 뜨립니다. 완료되면 해당 라인을 제거하는 것을 잊지 마십시오.

업데이트: 대안으로 #if DEBUG Pragmas, 당신은 또한 사용할 수 있습니다 Conditional("DEBUG_SERVICE") 기인하다.

[Conditional("DEBUG_SERVICE")]
private static void DebugMode()
{
    Debugger.Break();
}

너의 OnStart, 그냥이 방법을 호출하십시오.

public override void OnStart()
{
     DebugMode();
     /* ... do the rest */
}

여기에서 코드는 디버그 빌드 중에 만 활성화됩니다. 당신이 그것을 사용하는 동안, 서비스 디버깅을위한 별도의 빌드 구성을 만드는 것이 유용 할 수 있습니다.

다른 팁

또한 일반 실행을위한 별도의 "버전"을 가지고 있다고 생각하지만 서비스가 진행되는 방법이라고 생각하지만 그 목적을 위해 별도의 명령 줄 스위치를 전용해야합니까?

당신은 그냥 할 수 없었습니다 :

public static int Main(string[] args)
{
  if (!Environment.UserInteractive)
  {
    // Startup as service.
  }
  else
  {
    // Startup as application
  }
}

"혜택"이있을 것입니다. d F5 Visual Studio에서 (프로젝트 설정을 수정할 필요없이 /console 옵션).

기술적으로 Environment.UserInteractive 인지 확인합니다 WSF_VISIBLE 현재 윈도우 스테이션에 플래그가 설정되어 있지만 돌아올 다른 이유가 있습니까? false, (비 중과 적) 서비스로 운영되는 것 외에?

몇 주 전에 새로운 서비스 프로젝트를 설립했을 때이 게시물을 찾았습니다. 훌륭한 제안이 많이 있지만 여전히 원하는 솔루션을 찾지 못했습니다. 서비스 클래스에 전화 할 수있는 가능성 ' OnStart 그리고 OnStop 서비스 클래스를 수정하지 않은 방법.

내가 제시 한 솔루션은 다음을 사용합니다 Environment.Interactive 이 게시물에 대한 다른 답변에서 제안한대로 선택한 실행 모드.

static void Main()
{
    ServiceBase[] servicesToRun;
    servicesToRun = new ServiceBase[] 
    {
        new MyService()
    };
    if (Environment.UserInteractive)
    {
        RunInteractive(servicesToRun);
    }
    else
    {
        ServiceBase.Run(servicesToRun);
    }
}

그만큼 RunInteractive 도우미는 반사를 사용하여 보호를 호출합니다 OnStart 그리고 OnStop 행동 양식:

static void RunInteractive(ServiceBase[] servicesToRun)
{
    Console.WriteLine("Services running in interactive mode.");
    Console.WriteLine();

    MethodInfo onStartMethod = typeof(ServiceBase).GetMethod("OnStart", 
        BindingFlags.Instance | BindingFlags.NonPublic);
    foreach (ServiceBase service in servicesToRun)
    {
        Console.Write("Starting {0}...", service.ServiceName);
        onStartMethod.Invoke(service, new object[] { new string[] { } });
        Console.Write("Started");
    }

    Console.WriteLine();
    Console.WriteLine();
    Console.WriteLine(
        "Press any key to stop the services and end the process...");
    Console.ReadKey();
    Console.WriteLine();

    MethodInfo onStopMethod = typeof(ServiceBase).GetMethod("OnStop", 
        BindingFlags.Instance | BindingFlags.NonPublic);
    foreach (ServiceBase service in servicesToRun)
    {
        Console.Write("Stopping {0}...", service.ServiceName);
        onStopMethod.Invoke(service, null);
        Console.WriteLine("Stopped");
    }

    Console.WriteLine("All services stopped.");
    // Keep the console alive for a second to allow the user to see the message.
    Thread.Sleep(1000);
}

이것은 필요한 모든 코드이지만 나도 썼습니다. 연습 설명과 함께.

때로는 무슨 일이 일어나고 있는지 분석하는 것이 중요합니다. 서비스가 시작되는 동안. 서비스가 시작되는 동안 디버거를 첨부하기에 충분히 빠르지 않기 때문에 프로세스에 첨부하는 것은 도움이되지 않습니다.

짧은 대답은 다음을 사용하고 있다는 것입니다. 4 줄의 코드 이것을하기 위해:

#if DEBUG
    base.RequestAdditionalTime(600000); // 600*1000ms = 10 minutes timeout
    Debugger.Launch(); // launch and attach debugger
#endif

이것들은 OnStart 다음과 같이 서비스 방법 :

protected override void OnStart(string[] args)
{
    #if DEBUG
       base.RequestAdditionalTime(600000); // 10 minutes timeout for startup
       Debugger.Launch(); // launch and attach debugger
    #endif
    MyInitOnstart(); // my individual initialization code for the service
    // allow the base class to perform any work it needs to do
    base.OnStart(args);
}

전에하지 않은 사람들을 위해 아래에 자세한 힌트, 당신은 쉽게 붙잡을 수 있기 때문에. 다음 힌트는 참조합니다 Windows 7x64 그리고 Visual Studio 2010 팀 에디션, 그러나 다른 환경에도 유효해야합니다.


중요한: 서비스를 배치하십시오 "매뉴얼"모드 (어느 쪽이든 InstallUtil VS 명령 프롬프트의 유틸리티 또는 준비한 서비스 설치 프로그램 프로젝트를 실행하십시오). Visual Studio를 열었습니다 ~ 전에 서비스를 시작하고 서비스 소스 코드가 포함 된 솔루션을로드합니다. 서비스 제어판.

때문에 Debugger.Launch 코드, 이것은 대화 상자가 발생합니다. serviceName.exe. "나타나려면. 클릭하십시오 Elevate 예, 디버그 serviceName.exe 스크린 샷에 표시된대로 :
FrameworkException

그 후 Windows 7 UAC에서 Escpecially에서 관리자 자격 증명을 입력하라는 메시지가 표시 될 수 있습니다. 입력하고 진행하십시오 :

UACPrompt

그 후, 잘 알려져 있습니다 Visual Studio Just-In-Time Debugger 창 나타납니다. 정의 디버거를 사용하여 디버그 할 것인지 묻습니다. 클릭하기 전에 , 당신을 선택하십시오 새 인스턴스를 열고 싶지 않습니다 (두 번째 옵션) - 소스 코드가 표시되지 않기 때문에 새 인스턴스가 도움이되지 않습니다. 따라서 이전에 열린 비주얼 스튜디오 인스턴스를 대신 선택합니다.VSDebuggerPrompt

클릭 한 후 , 잠시 후 Visual Studio는 Debugger.Launch 진술은 코드를 디버깅 할 수 있습니다 (메서드 MyInitOnStart, 초기화가 포함되어 있음).VSDebuggerBreakpoint

압박 F5 즉시 실행을 계속하고 다음 다음 중단 점이 준비 될 때까지 준비됩니다.

힌트: 서비스를 계속 실행하려면 선택하십시오 디버그 -> 모두를 분리하십시오. 이를 통해 서비스가 올바르게 시작된 후 서비스와 통신하는 클라이언트를 실행할 수 있으며 시작 코드 디버깅이 완료되었습니다. 당신이 누르면 옮기다+F5 (디버깅 중지), 서비스가 종료됩니다. 이 작업을 수행하는 대신 사용해야합니다 서비스 제어판 그것을 멈추기 위해.

메모 저것

  • 당신이 a 풀어 주다, 그럼 디버그 코드가 자동으로 제거됩니다 서비스는 정상적으로 실행됩니다.

  • 나는 사용 중입니다 Debugger.Launch(), 어느 디버거를 시작하고 첨부합니다. 나는 테스트했다 Debugger.Break() 뿐만 아니라 작동하지 않았다, 서비스 시동시 디버거가 부착되지 않았기 때문에 아직 "오류 1067 : 프로세스가 예기치 않게 종료되었습니다.").

  • RequestAdditionalTime 더 오래 설정합니다 서비스 시작 시간 초과 (그것은이다 ~ 아니다 코드 자체를 지연 시키지만 즉시 계속됩니다. Debugger.Launch 성명). 그렇지 않으면 서비스를 시작하기위한 기본 시간 초과가 너무 짧고 전화를하지 않으면 서비스를 시작합니다. base.Onstart(args) 디버거에서 충분히 빠르게. 실제로 10 분의 시간 초과는 메시지를 보지 못하게합니다. "서비스가 응답하지 않았습니다 ... " 디버거가 시작된 직후.

  • 일단 익숙해지면이 방법은 매우 쉽습니다. 4 줄을 추가하십시오 기존 서비스 코드로 신속하게 제어 및 디버그를 얻을 수 있습니다.

내가 일반적으로하는 일은 별도의 클래스에서 서비스 논리를 캡슐화하고 '러너'클래스에서 시작하는 것입니다. 이 러너 클래스는 실제 서비스이거나 콘솔 응용 프로그램 일 수 있습니다. 따라서 솔루션에는 (적어도) 3 개의 프로젝트가 있습니다.

/ConsoleRunner
   /....
/ServiceRunner
   /....
/ApplicationLogic
   /....

이것 Fabio Scopel의 YouTube 비디오 Windows 서비스를 아주 멋지게 디버깅하는 방법을 설명합니다 ... 실제 수행 방법은 비디오에서 4:45에서 시작합니다 ...

다음은 비디오에 설명 된 코드입니다 ... 프로그램 파일에서 디버그 섹션에 대한 것들을 추가하십시오 ...

namespace YourNamespace
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
#if DEBUG
            Service1 myService = new Service1();
            myService.OnDebug();
            System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
#else
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[]
            {
                new Service1()
            };
            ServiceBase.Run(ServicesToRun);
#endif

        }
    }
}

Service1.cs 파일에서 ondebug () 메소드를 추가하십시오 ...

    public Service1()
    {
        InitializeComponent();
    }

    public void OnDebug()
    {
        OnStart(null);
    }

    protected override void OnStart(string[] args)
    {
        // your code to do something
    }

    protected override void OnStop()
    {
    }

작동 방식

기본적으로 당신은 a를 만들어야합니다 public void OnDebug() 그것은 그것을 부릅니다 OnStart(string[] args) 보호되고 외부에 접근 할 수 없으므로. 그만큼 void Main() 프로그램이 추가됩니다 #if 전처리 #DEBUG.

Visual Studio가 정의합니다 DEBUG 프로젝트가 디버그 모드에서 컴파일되는 경우 조건이 참을 때 디버그 섹션 (아래)이 실행할 수 있습니다.

Service1 myService = new Service1();
myService.OnDebug();
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);

그리고 콘솔 애플리케이션처럼 실행됩니다. 일이 정상화되면 모드를 변경할 수 있습니다. Release 그리고 일반 else 섹션은 논리를 트리거합니다

업데이트

이 접근법은 가장 쉬운 것입니다.

http://www.codeproject.com/kb/dotnet/debugwinservices.aspx

나는 후손에 대한 원래 대답을 아래에 남겨 둡니다.


내 서비스에는 서비스가 정기적으로 작업 할 수 있는지 여부를 정기적으로 확인하기를 원할 때 타이머를 캡슐화하는 클래스가있는 경향이 있습니다.

우리는 수업을 시작하고 서비스 시작 중에 starteventLoop ()를 호출합니다. (이 클래스는 콘솔 앱에서도 쉽게 사용할 수 있습니다.)

이 디자인의 좋은 부작용은 서비스가 실제로 작동하기 전에 타이머를 설정하는 인수를 사용하여 디버거를 수동으로 첨부 할 시간이 있도록 사용될 수 있다는 것입니다.

추신 디버거를 수동으로 연결하는 방법 달리기 과정에 ...?

using System;
using System.Threading;
using System.Configuration;    

public class ServiceEventHandler
{
    Timer _timer;
    public ServiceEventHandler()
    {
        // get configuration etc.
        _timer = new Timer(
            new TimerCallback(EventTimerCallback)
            , null
            , Timeout.Infinite
            , Timeout.Infinite);
    }

    private void EventTimerCallback(object state)
    {
        // do something
    }

    public void StartEventLoop()
    {
        // wait a minute, then run every 30 minutes
        _timer.Change(TimeSpan.Parse("00:01:00"), TimeSpan.Parse("00:30:00");
    }
}

또한 다음을 수행했습니다 (이미 이전 답변에서 언급했지만 조건부 컴파일러 [#if] 플래그가있어 릴리스 빌드에서 발사를 피할 수 있습니다).

때때로 우리는 릴리스를 구축하는 것을 잊고 클라이언트 데모에서 실행되는 앱에서 디버거 브레이크를 잊어 버렸기 때문에 이런 식으로 그 일을 중단했습니다.

#if DEBUG
if (!System.Diagnostics.Debugger.IsAttached)
{
    System.Diagnostics.Debugger.Break();
}
#endif

static void Main()
{
#if DEBUG
                // Run as interactive exe in debug mode to allow easy
                // debugging.

                var service = new MyService();
                service.OnStart(null);

                // Sleep the main thread indefinitely while the service code
                // runs in .OnStart

                Thread.Sleep(Timeout.Infinite);
#else
                // Run normally as service in release mode.

                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[]{ new MyService() };
                ServiceBase.Run(ServicesToRun);
#endif
}

명령 프롬프트 (sc.exe)를 통해 서비스를 시작할 수도 있습니다.

개인적으로, 나는 디버깅 단계에서 독립형 프로그램으로 코드를 실행했으며, 대부분의 버그가 해결되면 서비스로 실행되도록 변경합니다.

내가했던 일은 프로그램을 서비스 또는 정기 응용 프로그램으로 시작하는 명령 줄 스위치를 갖는 것이 었습니다. 그런 다음 IDE에서 코드를 통해 스위치를 설정할 수 있습니다.

일부 언어를 사용하면 실제로 IDE에서 실행 중인지 감지 하고이 스위치를 자동으로 수행 할 수 있습니다.

어떤 언어를 사용하고 있습니까?

사용 상단 핀 도서관.

콘솔 애플리케이션을 작성한 다음 기본에서 설정을 구성하십시오.

class Program
    {
        static void Main(string[] args)
        {
            HostFactory.Run(x =>
            {

                // setup service start and stop.
                x.Service<Controller>(s =>
                {
                    s.ConstructUsing(name => new Controller());
                    s.WhenStarted(controller => controller.Start());
                    s.WhenStopped(controller => controller.Stop());
                });

                // setup recovery here
                x.EnableServiceRecovery(rc =>
                {
                    rc.RestartService(delayInMinutes: 0);
                    rc.SetResetPeriod(days: 0);
                });

                x.RunAsLocalSystem();
            });
        }
}

public class Controller
    {
        public void Start()
        {

        }

        public void Stop()
        {

        }
    }

서비스를 디버깅하려면 Visual Studio에서 F5를 누르십시오.

서비스를 설치하려면 CMD "Console.exe 설치"를 입력하십시오.

그런 다음 Windows Service Manager에서 서비스를 시작하고 중지 할 수 있습니다.

나는 그것이 당신이 사용하는 OS에 달려 있다고 생각합니다. Vista는 세션 간의 분리로 인해 서비스에 첨부하기가 훨씬 어렵다고 생각합니다.

내가 과거에 사용한 두 가지 옵션은 다음과 같습니다.

  • GFLAGS (Windows 용 디버깅 도구에서)를 사용하여 프로세스를위한 영구 디버거를 설정하십시오. 이것은 "이미지 파일 실행 옵션"레지스트리 키에 존재하며 매우 유용합니다. "데스크탑과 상호 작용"을 가능하게하려면 서비스 설정을 조정해야한다고 생각합니다. 서비스뿐만 아니라 모든 유형의 디버깅에 이것을 사용합니다.
  • 다른 옵션은 코드를 약간 분리하여 서비스 부품을 일반 앱 시작과 교환 할 수 있도록하는 것입니다. 이렇게하면 간단한 명령 줄 플래그를 사용하여 서비스가 아닌 프로세스로 시작하여 디버깅하기가 훨씬 쉽습니다.

도움이 되었기를 바랍니다.

서비스를 작성할 때 모든 서비스 로직을 DLL 프로젝트에 넣고이 DLL에 호출하는 두 개의 "호스트"를 만듭니다. 하나는 Windows 서비스이고 다른 하나는 명령 줄 응용 프로그램입니다.

명령 줄 애플리케이션을 사용하여 디버깅을 사용하고 명령 줄 응용 프로그램에서 재현 할 수없는 버그에 대해서만 디버거를 실제 서비스에만 첨부합니다.

나는이 접근법을 사용합니다. 실제 서비스에서 실행 중에 모든 코드를 테스트해야한다는 것을 기억하지만, 명령 줄 도구는 멋진 디버깅 보조금이므로 다른 환경이며 실제 서비스와 똑같이 행동하지 않습니다.

onstart ()의 초기화를 포함하여 서비스의 모든 측면을 디버깅 할 수 있고 SCM의 프레임 워크 내에서 완전한 서비스 동작으로 실행하는 동시에 "콘솔"또는 "앱"모드를 실행할 수 있습니다.

동일한 프로젝트에서 디버깅에 사용하기 위해 두 번째 서비스를 만들어이 작업을 수행합니다. Debug Service는 평소와 같이 시작했을 때 (예 : 서비스 MMC 플러그인에서) 서비스 호스트 프로세스를 만듭니다. 이렇게하면 아직 실제 서비스를 시작하지 않았지만 디버거를 첨부하는 프로세스를 제공합니다. 디버거를 프로세스에 첨부 한 후 실제 서비스를 시작하면 onstart ()를 포함하여 서비스 라이프 사이클의 어느 곳에서나 나눌 수 있습니다.

코드 침입이 매우 적기 때문에 디버그 서비스를 서비스 설정 프로젝트에 쉽게 포함시킬 수 있으며 단일 코드 라인을 댓글을 달고 단일 프로젝트 설치 프로그램을 삭제하여 프로덕션 릴리스에서 쉽게 제거됩니다.

세부:

1) 구현 중이라고 가정합니다 MyService, 또한 생성 MyServiceDebug. 둘 다를 추가하십시오 ServiceBase 배열 Program.cs 그렇게 :

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    static void Main()
    {
        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[] 
        { 
            new MyService(),
            new MyServiceDebug()
        };
        ServiceBase.Run(ServicesToRun);
    }

2) 서비스 프로젝트의 프로젝트 설치 프로그램에 실제 서비스 및 디버그 서비스를 추가하십시오.

enter image description here

서비스 프로젝트 출력을 서비스의 설정 프로젝트에 추가 할 때 서비스 (Real 및 Debug)가 모두 포함됩니다. 설치 후 두 서비스 모두 Service.msc MMC 플러그인에 나타납니다.

3) MMC에서 디버그 서비스를 시작하십시오.

4) Visual Studio에서 디버그 서비스에서 시작된 프로세스에 디버거를 연결하십시오.

5) 실제 서비스를 시작하고 디버깅을 즐기십시오.

When developing and debugging a Windows service I typically run it as a console application by adding a /console startup parameter and checking this. Makes life much easier.

static void Main(string[] args) {
    if (Console.In != StreamReader.Null) {
        if (args.Length > 0 && args[0] == "/console") {
            // Start your service work.
        }
    }
}

How about Debugger.Break() in the first line?

To debug Windows Services I combine GFlags and a .reg file created by regedit.

  1. Run GFlags, specifying the exe-name and vsjitdebugger
  2. Run regedit and go to the location where GFlags sets his options
  3. Choose "Export Key" from the file-menu
  4. Save that file somewhere with the .reg extension
  5. Anytime you want to debug the service: doubleclick on the .reg file
  6. If you want to stop debugging, doubleclick on the second .reg file

Or save the following snippets and replace servicename.exe with the desired executable name.


debugon.reg:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\servicename.exe]
"GlobalFlag"="0x00000000"
"Debugger"="vsjitdebugger.exe"

debugoff.reg:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\servicename.exe]
"GlobalFlag"="0x00000000"

For routine small-stuff programming I've done a very simple trick to easily debug my service:

On start of the service, I check for a command line parameter "/debug". If the service is called with this parameter, I don't do the usual service startup, but instead start all the listeners and just display a messagebox "Debug in progress, press ok to end".

So if my service is started the usual way, it will start as service, if it is started with the command line parameter /debug it will act like a normal program.

In VS I'll just add /debug as debugging parameter and start the service program directly.

This way I can easily debug for most small kind problems. Of course, some stuff still will need to be debugged as service, but for 99% this is good enough.

#if DEBUG
    System.Diagnostics.Debugger.Break();
#endif

I use a variation on JOP's answer. Using command line parameters you can set the debugging mode in the IDE with project properties or through the Windows service manager.

protected override void OnStart(string[] args)
{
  if (args.Contains<string>("DEBUG_SERVICE"))
  {
    Debugger.Break();
  }
  ...
}

For trouble-shooting on existing Windows Service program, use 'Debugger.Break()' as other guys suggested.

For new Windows Service program, I would suggest using James Michael Hare's method http://geekswithblogs.net/BlackRabbitCoder/archive/2011/03/01/c-toolbox-debug-able-self-installable-windows-service-template-redux.aspx

Just put your debugger lunch anywhere and attach Visualstudio on startup

#if DEBUG
    Debugger.Launch();
#endif

Also you need to start VS as Administatrator and you need to allow, that a process can automatically be debugged by a diffrent user (as explained here):

reg add "HKCR\AppID{E62A7A31-6025-408E-87F6-81AEB0DC9347}" /v AppIDFlags /t REG_DWORD /d 8 /f

Use Windows Service Template C# project to create a new service app https://github.com/HarpyWar/windows-service-template

There are console/service mode automatically detected, auto installer/deinstaller of your service and several most used features are included.

Here is the simple method which I used to test the service, without any additional "Debug" methods and with integrated VS Unit Tests.

[TestMethod]
public void TestMyService()
{
    MyService fs = new MyService();

    var OnStart = fs.GetType().BaseType.GetMethod("OnStart", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);

    OnStart.Invoke(fs, new object[] { null });
}

// As an extension method
public static void Start(this ServiceBase service, List<string> parameters)
{
     string[] par = parameters == null ? null : parameters.ToArray();

     var OnStart = service.GetType().GetMethod("OnStart", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);

     OnStart.Invoke(service, new object[] { par });
}
static class Program
{
    static void Main()
    {
        #if DEBUG

        // TODO: Add code to start application here

        //    //If the mode is in debugging
        //    //create a new service instance
        Service1 myService = new Service1();

        //    //call the start method - this will start the Timer.
        myService.Start();

        //    //Set the Thread to sleep
        Thread.Sleep(300000);

        //    //Call the Stop method-this will stop the Timer.
        myService.Stop();

         #else
        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[] 
        { 
            new Service1() 
        };

        ServiceBase.Run(ServicesToRun);
         #endif
    }
}

You have two options to do the debugging.

  1. create a log file : Personally i prefer a separate log file like text file rather using the application log or event log.But this will cost you a lot on behalf of time, because its still hard to figure our where the exact error location is
  2. Convert the application to console application : this will enable you, all the debugging tools which we can use in VS.

Please refer THIS blog post that i created for the topic.

Just paste

Debugger.Break();

any where in you code.

For Example ,

internal static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        private static void Main()
        {
            Debugger.Break();
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[]
            {
                new Service1()
            };
            ServiceBase.Run(ServicesToRun);
        }
    }

It will hit Debugger.Break(); when you run your program.

The best option is to use the 'System.Diagnostics' namespace.

Enclose your code in if else block for debug mode and release mode as shown below to switch between debug and release mode in visual studio,

#if DEBUG  // for debug mode
       **Debugger.Launch();**  //debugger will hit here
       foreach (var job in JobFactory.GetJobs())
            {
                //do something 
            }

#else    // for release mode
      **Debugger.Launch();**  //debugger will hit here
     // write code here to do something in Release mode.

#endif
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top