.NET Worker Service: Create a background service in C# (run as a Windows Service)

Поделиться
HTML-код
  • Опубликовано: 28 сен 2024

Комментарии • 85

  • @RobertDavidson-i8p
    @RobertDavidson-i8p 20 дней назад

    I worked on my own little project for a full day. It would run fine from Visual Studio but as a Service it would time out and would not start. This was just from the very basic example that Visual Studio creates for you. I did not know you had to add the WindowsServices library. As soon as I did that and updated the program.cs, it worked like a charm. You saved me from crying. Thank you.

  • @dylanmckay1369
    @dylanmckay1369 Год назад +1

    Thanks for the help. This worked beautifully. Better than the Microsoft Tutorial.

  • @fedorpinega2507
    @fedorpinega2507 2 года назад +1

    Thanks for info, it allowed me to created my service. Special thanks for subs ;)
    Keep up the good work!

  • @edvardpotapenko
    @edvardpotapenko 2 года назад +3

    Thank you! Clear and simple

  • @JanManipol
    @JanManipol Месяц назад

    Thanks for the help. You're a savior.

  • @CamiloMejíaMonsalve
    @CamiloMejíaMonsalve Год назад

    thank you so much man, for your videos, for the time and the love that you put in them, you are pretty helpful for me

    • @RoundTheCode
      @RoundTheCode  Год назад

      Thanks Camilo. Glad you are enjoying the content.

  • @tommykahlow5353
    @tommykahlow5353 2 года назад

    Thank you for the tutorial! I wasn't adding in the Microsoft.Extensions.Hosting.WindowsServices to my project and I couldn't figure out why my service was failing to start. It would run and log for 30 seconds and then quit with a message saying "The service did not respond to the start or control request in a timely fashion."

    • @RoundTheCode
      @RoundTheCode  2 года назад

      Yes it can be hard to debug Windows Service's. Glad you managed to resolve the issue.

    • @softscrypt8474
      @softscrypt8474 Год назад

      When I run the consul, information is written in the logger
      ​ @Round The Code

  • @hassannoor6185
    @hassannoor6185 2 года назад +1

    Is there a follow up video on this topic?

    • @RoundTheCode
      @RoundTheCode  2 года назад

      Hi Hassan,
      What follow up video are you expecting?

  • @pillockmacpillock2463
    @pillockmacpillock2463 4 месяца назад

    Not sure I like this implementation. Where are the classic start and stop stubs you get in framework? Feels like the core version is a bit noddy

    • @RoundTheCode
      @RoundTheCode  4 месяца назад

      Are you talking about the WorkerService?
      It inherits the IHostedService interface which includes StartAsync and StopAsync methods. These can be overloaded through the WorkerService.
      This video has more details about it:
      ruclips.net/video/wfyqKXMfZHk/видео.html

  • @shreyasmahajan2157
    @shreyasmahajan2157 5 месяцев назад

    In my case everything worked perfectly as demonstrated except the deployment part.
    After creating the service using "sc" command, I am getting the following error :
    Windows Could not start the service on the local computer.
    Error 1053 : The service did not respond to the start or control request in a timely fashion.
    What is the reason for this error ?
    Thanks.

    • @RoundTheCode
      @RoundTheCode  5 месяцев назад

      You've either got the service name wrong, or there is a bug with your application. Make sure the service name you ran with the "sc" command matches what is in your app.

    • @shreyasmahajan2157
      @shreyasmahajan2157 4 месяца назад

      ​@@RoundTheCode
      Thanks for the reply!!
      Here is the the the way I am creating the service :
      sc create AIQuestionGeneration.WorkerService binpath="D:\Path\ToService\Build1\AIQuestionGeneration.WorkerService.exe" start="demand" displayname="AIQuestionGeneration.WorkerService"
      Any thing incorrect ? Or a Bug in my application ?

    • @shreyasmahajan2157
      @shreyasmahajan2157 4 месяца назад

      After banging my head for quite a few hours, I have sorted the issue.
      The issue was simple, the service was not able to find the app.settings.json file because I had used "Directory.GetCurrentDirectory()" in my Program.cs.
      As a result it was searching the file in the default location of system32.
      All what I had to do was change the path to : "Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)" and it worked in a second.
      The error which I got was not much informative. I had to visit the "Event Viewer" section in Windows to check the logs and figure out the exact error.

  • @stilllearningknowledge4529
    @stilllearningknowledge4529 3 месяца назад

    Thank you. Clear and simple. Nice explanation. Keep going

  • @guswind4636
    @guswind4636 2 года назад +1

    What if you would need to call another Background service from the main Worker Service?

    • @RoundTheCode
      @RoundTheCode  2 года назад

      Hi Gus,
      Would you want to trigger a background service to start from another Worker Service? Is that what you're asking?

    • @guswind4636
      @guswind4636 2 года назад

      @@RoundTheCode Yes I have one Hosted Worker Service that runs initially and at some point of its execution I want to start another "child" background process. I'm currently triggering the child process with "await Task.Run(() => ChildBackgroundProcess, cancelToken)" but I'm not sure whether that is the correct\clean way to do it

    • @RoundTheCode
      @RoundTheCode  2 года назад

      @@guswind4636 And I'm assuming you didn't add the child background process to the IoC/DI container as part of dependency injection? You just created a new instance of the child background process and ran it?

    • @guswind4636
      @guswind4636 2 года назад

      @@RoundTheCode yes I didn't add the child process to the DI container, it's just a child Process\Task that runs indefinitely as long as the main Worker Service runs

    • @RoundTheCode
      @RoundTheCode  2 года назад

      @@guswind4636 I personally don't see anything wrong with that, as long as the two tasks have some sort of relation, and the child task has to run on the parent task.

  • @bioanu
    @bioanu 2 года назад +1

    Thank you!! Excellent stuff! It is possible to add a SignalR hub server to our Worker service??

    • @RoundTheCode
      @RoundTheCode  2 года назад

      Hi bioan,
      A SignalR Hub requires a URL so clients can connect to it.
      As a .NET Worker Service is a background service rather than a web application, I would assume that you can't.
      However, you can run hosted services in ASP.NET Core and that would work. You could pass in your IHubContext into your hosted service as it has a Singleton service lifetime.
      Check out this video for more about ASP.NET Core hosted services.
      ruclips.net/video/IekoUio2Fek/видео.html

    • @bioanu
      @bioanu 2 года назад

      @@RoundTheCode Thank you very much!!!

  • @jigspatel-nu3ee
    @jigspatel-nu3ee 4 месяца назад

    Thank you it's working, explained very easy

  • @denissmith8282
    @denissmith8282 Год назад

    Nice and easy, thank you. Btw, you look like a South Park character prototype 🙂

  • @siavashmehmandoost2198
    @siavashmehmandoost2198 Год назад

    Thank you for the great tutorial! Is there any way to keep our windows service running even in sleep or hibernate mode? I just created a windows service and it's suspended (not stopped!) when I close the lid of the laptop.

    • @RoundTheCode
      @RoundTheCode  Год назад

      I'm not aware of anyway of doing it. If your computer is asleep, surely you wouldn't want it to be running any services?

  • @bill_1951
    @bill_1951 2 года назад

    .Net Framework services are able to receive custom commands via "protected override void OnCustomCommand(int Command)". Is equivalent functionality available in .Net 6? I've looked at many examples of creating .Net 6 Worker Services but they all seem to use timers to monitor or report something periodically, none of the examples show receiving custom commands from other applications.

    • @RoundTheCode
      @RoundTheCode  2 года назад

      Have a look at this. It might be what you're after? github.com/dotnet/runtime/issues/50021#issuecomment-547503684

  • @peterwilson71
    @peterwilson71 2 года назад

    I have a worker service and added the Setup Installer project but I haven't found a way to install the service using the installer. It works with sc.exe but how can I add this step to the installer?

    • @RoundTheCode
      @RoundTheCode  2 года назад

      You could have a look at the WiX Toolset. I have created installers for .NET Framework services in the past. Guessing you could use it for later .NET versions?
      wixtoolset.org/

  • @snldev
    @snldev Год назад

    I've developed a routine that reads/updates data from specific database and then do a looping in the rows and returns status information to another application (webhook). It repeats every 24 hours. It works in this BackgroundService approach, but is it a good pratice? There is no much data read in this process, I guess about 150 per day. Thanks

    • @RoundTheCode
      @RoundTheCode  Год назад +1

      Hi Leivas. It sounds good to me. Is it 24 hours after the app has started? Or is it at a specific time of day?

    • @snldev
      @snldev Год назад

      @@RoundTheCode it's at a specific time of day

  • @aniljain50
    @aniljain50 2 года назад +4

    Simple and excellent tutorial

  • @biproberkay
    @biproberkay Год назад

    thank you short and clear

    • @RoundTheCode
      @RoundTheCode  Год назад +1

      Thanks Şükrü. Glad you found the content useful.

  • @mhsn27mhsn10
    @mhsn27mhsn10 Месяц назад

    thank you Sir

  • @imterpsfan2
    @imterpsfan2 10 месяцев назад

    Nice example. I have an existing Windows Service application in .NET Framework that I'm migrating to a Worker Service. Because I am using some Windows-specific aspects in the service, such as reading Windows Event Logs (EventLogQuery) I'm assuming I will need to encapsulate this functionality in the .NET Standard and then reference that project in the worker service?
    Wait, I see System.Diagnostics.EventLog ia now in nuget package manager as a .NET Platform service so maybe I don't need to do this trick anymore? The answer is that I don't need to encapsulate the project in .NET Standard and then reference in .NET Core. I can do it directly! But I need the Windows Compatibility Pack.
    dotnet add package Microsoft.Windows.Compatibility --version 8.0.0
    dotnet add package System.Diagnostics.EventLog --version 8.0.0

    • @RoundTheCode
      @RoundTheCode  10 месяцев назад

      Looks like you've found out how to do it.

  • @robertlopez6134
    @robertlopez6134 2 года назад +1

    Thanks.

  • @adeni4359
    @adeni4359 2 года назад +2

    Love your channel. Please more long tutorials!

  • @duongchinhngu2407
    @duongchinhngu2407 10 месяцев назад +1

    Thank you so much, your video saved my day!

  • @toniobrados6736
    @toniobrados6736 2 года назад +1

    Good video... Is possible to make this service in an unstoppable service? Thanks

    • @RoundTheCode
      @RoundTheCode  2 года назад +1

      Hi Toni,
      Thanks for your comment. Just out of interest, why would you want an unstoppable service?

    • @toniobrados6736
      @toniobrados6736 2 года назад

      @@RoundTheCode Because the user should not stop it. It is a service that takes statistics from the computer.

    • @RoundTheCode
      @RoundTheCode  2 года назад +1

      @@toniobrados6736 Check out this StackOverflow post. A user has come up with a possible solution. stackoverflow.com/questions/70503859/is-there-a-way-to-disable-the-stop-button-in-windows-worker-services-background

  • @gahshunker
    @gahshunker 3 месяца назад

    how can this made cross platform? any nuget package to have a host that is not windows specific? great video btw, concise and to the point. thanks

  • @mikopanjean8756
    @mikopanjean8756 2 года назад +1

    Most Usefull Tutorial. Thank You!!

  • @khaqankhokhar3543
    @khaqankhokhar3543 Год назад +1

    great explaination

  • @PremKumar-kg5ep
    @PremKumar-kg5ep 2 года назад +1

    Very good explanations.

  • @moussakecibi1740
    @moussakecibi1740 2 года назад

    I like your video. But I have a question whom will send the cancellation token to workerservice? and whats thw role of the loop while? is it to keep the WorkerService running? Thank you in adavnce

    • @RoundTheCode
      @RoundTheCode  2 года назад

      Yes, the loop is to keep the Worker Service running. I believe the application will automatically send the cancellation token to the Worker Service when it stops.

  • @UnknownMoses
    @UnknownMoses 2 года назад

    In file explorer, if you hold Shift + Right Click, the context window gives you an option, "copy as path" this copies the full file path inside double quotes, so you can paste it anywhere. Annoyingly, in Windows 11, you probably have to click, show more options on the dumb Windows 11 context menu.

  • @richardokonicha
    @richardokonicha 2 года назад

    Hi @roundtheCode, could we have work services in a different language like python on azure? I have been struggling with this for a while

    • @RoundTheCode
      @RoundTheCode  2 года назад

      Hi Richard, unfortunately I don't know enough but Python to be able to answer your question.

  • @jps9355
    @jps9355 Год назад

    I am getting error 193 when i try to start the service. When i try to start it from the console it says that it is not a valid win32 aplication. Does anyone know what could be causing it?

    • @RoundTheCode
      @RoundTheCode  Год назад

      I would check that you have the correct filepath to the .exe file when you registered the Windows Service. If the filepath doesn't match, you are likely to see an error like that.

  • @coding-gemini
    @coding-gemini 9 месяцев назад

    Nicely explained Thank you, what are the other options for making it an automatic windows service, auto ?

  • @faridulhuk1248
    @faridulhuk1248 2 года назад

    Hi can we add multiple job into the worker service using (Quartz)

    • @RoundTheCode
      @RoundTheCode  2 года назад

      I've never used Quartz before, but I'm assuming you can do it.

  • @henkmaritz007
    @henkmaritz007 Год назад

    thanks, nice video