0

How do I use "StartService" Task with ThreadStart? Is it possible?

public partial class MyService : ServiceBase
{
    public MyService()
    {
        InitializeComponent();

        LocalInit();
    }

    internal void LocalInit()
    {
        //place here any local checks 
    }


    protected override void OnStart(string[] args)
    {
        if (Something.ConfigOK())
        {
            ThreadStart threadDelegate = Something.StartService; // Expected a method with void StartService signature
            var newThread = new Thread(threadDelegate);
            newThread.Start();
        }
        else
        {
            //log error
            throw new Exception("MyService : Config failed");
        }
    }
}



public static partial class Something
{
    public static async Task StartService()
    {
        await DoJob();
    }
}

Errors

Error CS0407 'Task Something.StartService()' has the wrong return type

Expected a method with void StartService signature

Gerald Hughes
  • 5,771
  • 20
  • 73
  • 131
  • The `Thread` constructor does not understand async delegates. You can read about this [here](https://stackoverflow.com/questions/44364092/is-it-ok-to-use-async-with-a-threadstart-method) or [here](https://stackoverflow.com/questions/30044846/async-thread-body-loop-it-just-works-but-how). Why are you starting a `Thread`, and don't just invoke the asynchronous method `DoJob` directly inside the `OnStart` method? – Theodor Zoulias Jul 09 '21 at 10:06
  • 2
    As a side note, according to the [guidelines](https://learn.microsoft.com/en-us/dotnet/standard/asynchronous-programming-patterns/task-based-asynchronous-pattern-tap#naming-parameters-and-return-types) the asynchronous methods should have an `Async` suffix. `StartServiceAsync` and `DoJobAsync` is correct. – Theodor Zoulias Jul 09 '21 at 10:08

2 Answers2

1

Have you tried this?

protected override void OnStart(string[] args)
{
    if (Something.ConfigOK())
    {
        Something.StartService();
    }
    else
    {
        //log error
        throw new Exception("MyService : Config failed");
    }
}

If DoJob os truly asynchronous or:

protected override void OnStart(string[] args)
{
    if (Something.ConfigOK())
    {
        Task.Run(Something.StartService);
    }
    else
    {
        //log error
        throw new Exception("MyService : Config failed");
    }
}

if it isn't (blocking).

There's no need to explicitly create a thread.

Beware of exception handling!

But, since you mention ASP.NET Core (???) I would recomend using a Worker template.

Paulo Morgado
  • 14,111
  • 3
  • 31
  • 59
0

It is possible, but I would suggest you to go with Background tasks with hosted services. Here is some implementation

Or use hangfire queues.

As I mentioned, this is a suggestion not a answer for your question.

cdev
  • 5,043
  • 2
  • 33
  • 32