2
\$\begingroup\$

Is there a better way to structure a method that returns a task that queues several inbound socket connections?

    public Task Start(CancellationToken token)
    {
        return Task.Run(
            () =>
            {
                var acceptCount = new SemaphoreSlim(10);
                while (!token.IsCancellationRequested)
                {
                    acceptCount.Wait(token);
                    if (token.IsCancellationRequested)
                        break;

                    var args = new SocketAsyncEventArgs();
                    args.UserToken = acceptCount;
                    args.Completed += AcceptInbound;
                    if (!this.socket.AcceptAsync(args))
                        AcceptInbound(this.socket, args);

                }
            }, 
            token);
    }
    private void AcceptInbound(object sender, SocketAsyncEventArgs e)
    {
        ((SemaphoreSlim)e.UserToken).Release();
        Socket connectedClient = e.AcceptSocket;
    }
\$\endgroup\$
2
  • 1
    \$\begingroup\$ Wouldn't Task.WaitAny(Task[]) help? \$\endgroup\$ Mar 17 '15 at 13:10
  • \$\begingroup\$ How are the connectedClients going to be processed further? What should happen if AcceptInbound() throws an exception? \$\endgroup\$
    – svick
    Apr 12 '15 at 15:51
2
\$\begingroup\$

I think Task.Factory.FromAsync is what you are looking for...

public async Task Start(CancellationToken token)
{
     while (!token.IsCancellationRequested)
     {
         Socket connectedClient = await AcceptAsync(this.socket).ConfigureAwait(false);
         ...
     }
}

public static Task<Socket> AcceptAsync(Socket socket)
{
     return Task.Factory.FromAsync<Socket>(socket.BeginAccept, socket.EndAccept, null);
}
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Except if you do it this way, you won't get any concurrency: you're always waiting for one socket at a time. \$\endgroup\$
    – svick
    Apr 12 '15 at 15:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.