Is it possible to use Session in Windows Service?

3

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

    
asked by anonymous 10.02.2015 / 18:40

1 answer

1

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();
    }
}
    
12.02.2015 / 18:39