Embedio: How to detect when server started listening?

Created on 1 Apr 2019  路  16Comments  路  Source: unosquare/embedio

How to wait server started listening event?

Currently I do the following hack:

        _task = _server.RunAsync();

        while (!_server.Listener.IsListening)
        {
            await Task.Delay(500);
            if (_task.Exception != null)
                throw new Exception("Error listen server", _task.Exception);

        }
enhancement

All 16 comments

We can probably add a state property, like Stopped, Loading, Running, Stopping... What do you think?

In my case I need to detect when server is started listening or failed because port is busy.

So I made such trick:

    public async Task StartListen()
    {
        if (_task != null)
            throw new Exception("Server already started");
        _task = _server.RunAsync();

        while (!_server.Listener.IsListening)
        {
            await Task.Delay(500);
            if (_task.Exception != null)
                throw new Exception("Error listen server", _task.Exception);

        }
    }

In my opinion it would be better if WebServer had method Task WaitForListen()

Another idea is WebServer should have event which signals about started listening.
Then it will be possible for trick similar to https://stackoverflow.com/a/19104345

I like the idea of events, probably a single event StateChanged. What do you think?

I like the idea of events, probably a single event StateChanged. What do you think?

Yeah, fine. This will solve the problem of detecting when this happened.

I created a new branch for this issue: Issue257-WebServerEvent

What do you think?

Term "Running" is not clear. But "Listening" has only one meaning for everybody in my opinion.
How do you think?

Makes sense. I'll change it.

Done!

Thanks!

I'll release this version probably tomorrow.

I just published the new Nuget v2.5.0. Can I close this issue?

Hi.

Looks like there is not enough something.

I started 3 servers on port 666 in the same time.
First all of them sent me State = Loading. Then one of them sent me State = Listening.
2 other servers have not sent any event.

So again I can't detect when 2 other servers failed to start listening.
I am sorry, probably I didn't explain my problem clearly.

So currently the only way to detect error when starting listening is to check Exception on Task.

Okay, I got it.

    public async Task StartListen()
    {
        if (_task != null)
            throw new Exception("Server already started");

        var tcs = new TaskCompletionSource<object>();

        _server.StateChanged += (sender, e) =>
        {
            if (e.NewState == WebServerState.Listening)
                tcs.SetResult(null);
        };

        _task = _server.RunAsync();

        await await Task.WhenAny(tcs.Task, _task);
    }

But it works only if I add event handler before _server.RunAsync(). And this is logically.

Was this page helpful?
0 / 5 - 0 ratings