Is it possible to use Session in Windows Service?

Asked

Viewed 101 times

3

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

  • 1

    It would be interesting for you to better detail the question. Do you need to save the status of what? When? Why? Has the code to understand?

  • I have a Timer in the service, which runs a certain routine that can take longer beyond the execution of the next Timer, so obviously I don’t want to let it run again while this first Timer is running, I don’t want to put this in the database, would like in some way to identify this in the application itself.

  • @Raí, I would like to suggest the following reading: http://weblogs.asp.net/jongalloway//428303

1 answer

1


You can store it in an object. "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();
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.