I have a TcpListener, which can be started
public void Start()
{
if (!Listening && !IsDisposed)
{
_socket.Bind(_localEndpoint);
Task.Run(DoListen);
}
}
private async Task DoListen()
{
_socket.Listen();
Listening = true;
try
{
while (Listening)
{
var socket = await _socket.AcceptAsync().ConfigureAwait(false);
NewConnection?.Invoke(new Connection(socket));
}
}
catch (SocketException e)
{
Stop();
}
finally
{
Listening = false;
}
}
and stopped
public void Stop()
{
_socket?.Close();
IsDisposed = true;
Listening = false;
}
How can I cancel the Task started by calling Start()
?
By making the loops condition Listening
, I can ensure that the task will stop when the condition is evaluated.
However, this would only happen, after a new connection is accepted.
How can I get out of awaiting var socket = await _socket.AcceptAsync().ConfigureAwait(false);
?
What happends if the associated socket is closed whilst awaiting AcceptAsync()
?
Thanks for your answers!
CodePudding user response:
Use a CancellationTokenSource. You can then provide a cancellation Token (cts.Token) to the method DoListen(CancellationToken token).
Within DoListen check cancellation in the while loop using the property IsCancellationRequested and pass the token to the Socket by using AcceptAsync(CancellationToken) method.