C
C#12mo ago
iskander

❔ ✅ (SOLVED) TcpListener.AcceptTcpClientAsync does not get cancelled

CancellationTokenSource cancel = new(400);

TcpClient JoinedClient = await Server.AcceptTcpClientAsync(cancel.Token);
CancellationTokenSource cancel = new(400);

TcpClient JoinedClient = await Server.AcceptTcpClientAsync(cancel.Token);
so i expect this code to accept any tcp clients and if a 400ms period pass it will cancel but for whatever reason AcceptTcpClientAsync keeps halting my execution! i could probably run my own wait timer and if the timer finishes then i will call TcpListener.Stop() but i can see how that workaround would cause issues for in the future. and one odd thing is when a tcp client successfully connects to the server the function doesnt finish execution oddly
10 Replies
cap5lut
cap5lut12mo ago
are u handling the cancellation exception?
MODiX
MODiX12mo ago
cap5lut
REPL Result: Success
using System.Diagnostics;
using System.Net.Sockets;

var listener = new TcpListener(System.Net.IPAddress.Any, 55555);
listener.Start();

var cts = new CancellationTokenSource(400);
var sw = Stopwatch.StartNew();
try
{
await listener.AcceptTcpClientAsync(cts.Token);
}
catch(Exception e)
{
Console.WriteLine(e);
}
finally
{
sw.Stop();
Console.WriteLine(sw.Elapsed);
}

listener.Stop();
using System.Diagnostics;
using System.Net.Sockets;

var listener = new TcpListener(System.Net.IPAddress.Any, 55555);
listener.Start();

var cts = new CancellationTokenSource(400);
var sw = Stopwatch.StartNew();
try
{
await listener.AcceptTcpClientAsync(cts.Token);
}
catch(Exception e)
{
Console.WriteLine(e);
}
finally
{
sw.Stop();
Console.WriteLine(sw.Elapsed);
}

listener.Stop();
Console Output
System.OperationCanceledException: The operation was canceled.
at System.Threading.CancellationToken.ThrowOperationCanceledException()
at System.Threading.CancellationToken.ThrowIfCancellationRequested()
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError error, CancellationToken cancellationToken)
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.System.Threading.Tasks.Sources.IValueTaskSource<System.Net.Sockets.Socket>.GetResult(Int16 token)
at System.Net.Sockets.TcpListener.<AcceptTcpClientAsync>g__WaitAndWrap|31_0(ValueTask`1 task)
at Submission#0.<<Initialize>>d__0.MoveNext()
00:00:00.4022679
System.OperationCanceledException: The operation was canceled.
at System.Threading.CancellationToken.ThrowOperationCanceledException()
at System.Threading.CancellationToken.ThrowIfCancellationRequested()
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError error, CancellationToken cancellationToken)
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.System.Threading.Tasks.Sources.IValueTaskSource<System.Net.Sockets.Socket>.GetResult(Int16 token)
at System.Net.Sockets.TcpListener.<AcceptTcpClientAsync>g__WaitAndWrap|31_0(ValueTask`1 task)
at Submission#0.<<Initialize>>d__0.MoveNext()
00:00:00.4022679
Compile: 680.802ms | Execution: 506.433ms | React with ❌ to remove this embed.
iskander
iskander12mo ago
im handling An expectation 😅 ok i gonna try to catch but shouldn't VS break execution when an exception is thrown? yep that did it! thanks a lot @cap5lut
cap5lut
cap5lut12mo ago
in some situations it doesnt, for example if u do not await a task where its thrown in this is the way to $close the thread:
MODiX
MODiX12mo ago
Use the /close command to mark a forum thread as answered
iskander
iskander12mo ago
yeah but i did await the task ig im missing something...good excuse to research some more about C# heh
cap5lut
cap5lut12mo ago
well, dunno. maybe the code u where u await is already in an unawaited task this for example doesnt make VS pause execution
_ = Task.Run(async () =>
{
var listener = new TcpListener(System.Net.IPAddress.Any, 55555);
listener.Start();

var cts = new CancellationTokenSource(400);
var sw = Stopwatch.StartNew();
await listener.AcceptTcpClientAsync(cts.Token);
sw.Stop();
Console.WriteLine(sw.Elapsed);

listener.Stop();
});
_ = Task.Run(async () =>
{
var listener = new TcpListener(System.Net.IPAddress.Any, 55555);
listener.Start();

var cts = new CancellationTokenSource(400);
var sw = Stopwatch.StartNew();
await listener.AcceptTcpClientAsync(cts.Token);
sw.Stop();
Console.WriteLine(sw.Elapsed);

listener.Stop();
});
using await Task.Run(...); instead makes it pause
iskander
iskander12mo ago
umm yeah that could be it. i called the task while i was doing some other operations thanks a lot cap! you've been extremely helpful 😊
cap5lut
cap5lut12mo ago
glad i could help o7
Accord
Accord12mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server
More Posts
✅ Tracking changes on a complex object provided by a third party libraryHi! I have a third party .Net Framework dll that allows me to load a file. This file is potentially ❔ ✅ How I can fix download and unzipI wrote a code to download the archive and unpack it but it just creates empty files instead of deco❔ Error message: Cannot convert query to sqlhi i have this code, on line 119 is whats causing the error saying the query cannot be converted to Make a method acessable by scripts extending it, but not by outside scriptsI have private which limits a method to itself, and I have public which lets anything access the metOk so i DID NOT add hello world to my code but it still appearsmy code for some ungodly reason has decided to not use my code and use a previous code when i run an❔ Problem with Quick SortIt seems that it partially sorts it and doesn't finish. I really can't see what is wrong ``` void Qu"name space 'helloworld2' already contains a definition for a 'program'Man this my first code ever in c# it worked two seconds ago and now it dont what do i do pls heres t❔ Windows forms C#Issue with forms resizing when maximizing the window, how do i get rid if the empty space?graphUser almost fully NULL - Graph APIWhen I'm reading the profile and wanting to collect all of it's outlook contacts it's says NULL even❔ Why doesn't every method in Collection<T> has an extension point?For example, `Insert` calls `InsertItem`, and `InsertItem` by default calls `items.Insert(index, ite