c# – Is it possible to use Session on Windows Service?

Question:

I have a Windows Service application, and I need to save the state while a certain method is executed, what is the best way to do this?

Answer:

You can store in an object. The "Service" is an instance of your class, so you can store anything inside it.

public class MyTask
{
    public void LongOperation()
    {
        // seu código que pode demorar aqui
    }

    public Task LongOperationAsync()
    {
        return Task.Run(delegate () { this.LongOperation(); });
    }
}

public class MyService : ServiceBase
{
    Timer _timer;
    MyTask _currentTask;
    bool _called;

    protected override void OnStart(string[] args)
    {
        base.OnStart(args);
        _currentTask = new MyTask();
        _called = false;
        _timer = new Timer(5000);
        _timer.Elapsed += TimerElapsed;
        _timer.Start();
    }

    private async void TimerElapsed(object sender, ElapsedEventArgs e)
    {
        // TODO:
        //      talvez você precise usar uma sincronização à nível de Thread (lock) aqui
        if (_called)
        {
            // função ja foi chamada
            return;
        }
        _called = true;
        await _currentTask.LongOperationAsync();
        _called = false;
    }

    protected override void OnStop()
    {
        _timer.Stop();
        base.OnStop();
    }
}
Scroll to Top
AllEscort