简体   繁体   中英

Task in C# windows service does not log when elapsed by timer

I have written a windows service in C# where I called an asynchrnous Task at OnStart(), OnStop() and a elapsed callback of a timer ticks every 30 seconds. The task looks like below:

    private async void WriteLog(WorkerLog worker)
    {
        string x = await Logger.WriteLogAsync(worker);
        Logger.WriteError(x);
    }

The problem I am facing is I can see my logger is logging when OnStart is called. But timer elapsed callback is not logging. Also when I stop the service from service explorer, it does log either. I have tested the service without this async call it logs in every tick and OnStop().

Can anyone pin point my thought what should I consider before calling async call in windows service timer tick calls?

For taking idea how my elapsed timer ticker looks like:

    private void workerTimer_Tick(object sender, ElapsedEventArgs e)
    {
        // Write code here to do some job depends on your requirement
        worker.Message = "Scheduler timer ticked and some job has been done successfully.";
        WriteLog(worker);
    }

The timer created at OnStart()

    protected override void OnStart(string[] args)
    {
        workerTimer = new System.Timers.Timer();
        this.workerTimer.Interval = 30000; // every 30 secs
        this.workerTimer.Elapsed += new System.Timers.ElapsedEventHandler(this.workerTimer_Tick);
        this.workerTimer.Enabled = true;
        this.workerTimer.AutoReset = false;

        ..............
    }

You are invoking async method from synchronous method so if there is any exception thrown by async method then it would not be captured by synchronous method as async method thread context will not merge to your synchronous call. In general, having async void methods makes harder to test the program - but the ability was precisely given for the entry point event handlers.

What you can do now : 1. Change the WriteLog method like below

private async Task WriteLog(WorkerLog worker)

Also, invoke this WriteLog method from synchronous method like

 Task.Run(async () => { await WriteLog(worker); });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM