WatsonTcp icon indicating copy to clipboard operation
WatsonTcp copied to clipboard

Incomplete Dispose of WatsonTCPServer

Open sancheolz opened this issue 1 year ago • 2 comments

This test fails starting from 6.0 version of WatsonTCP:

var server = new WatsonTcpServer("127.0.0.1", 9000);
server.Events.MessageReceived += (_, _) => { Console.WriteLine("srecv"); };
server.Start();
var client = new WatsonTcpClient("127.0.0.1", 9000);
client.Events.MessageReceived += (_, _) => { Console.WriteLine("crecv"); };
client.Connect();
Task.Run(() => { client.SendAsync("aaa"); });
server.Dispose();

It throws

System.AggregateException : One or more errors occurred. (A task was canceled.)
  ----> System.Threading.Tasks.TaskCanceledException : A task was canceled.
   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
   at System.Threading.Tasks.Task.Wait()
   at WatsonTcp.WatsonTcpServer.Dispose(Boolean disposing) in WatsonTcpServer.cs:line 621

sancheolz avatar Nov 14 '24 08:11 sancheolz

Hi ,

Task.Run(() => { client.SendAsync("aaa"); });

You are executing the SendAsync in the Fire And Forget Task !

Which means the server.Dispose() will be called Before the completion of SendAsync.

Try this two options :

client.SendAsync("aaa").GetAwaiter.GetResult(); ( without Task.Run) and see what happens.

Or

await client.SendAsync("aaa");

Hope this helps.👍

ShayanFiroozi avatar Jan 15 '25 07:01 ShayanFiroozi

@ShayanFiroozi Hi. The client can be on another machine and send messages independently from the server. This example simulates such a scenario. So waiting doesn't make sense.

sancheolz avatar Jan 15 '25 15:01 sancheolz

Moving this to discussion. The right approach is to await the client.SendAsync so that it has to complete before the server is disposed.

jchristn avatar Oct 25 '25 02:10 jchristn