0
votes

I have TCP Client from

System.Net.Sockets

public async void startTCP()
{
    await client.ConnectAsync(IPAddress, port);
    stream = client.GetStream();
}

I surround it with try catch block but when I run the code and this exception is raised and VS shows that I'm at

UnhandledException += (sender, e) =>
{
    if (global::System.Diagnostics.Debugger.IsAttached) 
        global::System.Diagnostics.Debugger.Break();
};

in App.g.i.cs not where I want to be => Handle the exception myself

System.Net.Internals.SocketExceptionFactory+ExtendedSocketException: The requested address is not valid in its context 255.255.255.255:25565 at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult) at System.Net.Sockets.TcpClient.EndConnect(IAsyncResult asyncResult) at System.Net.Sockets.TcpClient.<>c.b__21_1(IAsyncResult asyncResult) at System.Threading.Tasks.TaskFactory1.FromAsyncCoreLogic(IAsyncResult iar, Func2 endFunction, Action1 endAction, Task1 promise, Boolean requiresSynchronization) --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter.GetResult() at PersonDesk.Socket.d__10.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<>c.b__6_0(Object state) at System.Threading.WinRTSynchronizationContext.Invoker.InvokeCore()}

The IP address is just placeholder for the exception to be raised

1
where is the try...catch??NicoRiff
Is the try-catch inside of the startTCP method, or is it where you call it? async void means startTCP is fire and forget so you're not going to be able to handle exceptions outside of the method.juharr
use "public async Task StartTcpAsync()" instead of "public async void startTCP()"tzm
The try catch is outside StartTCP, it's where I call it.Evžen Křídlo

1 Answers

2
votes
public async void startTCP()

is an async void. You shouldn't do that. Because

I surround it with try catch block

and that is the one thing that doesn't work for async void.


For a complete answer you will have to show how startTCP() is called. The complete call chain is involved.

It seems to be about WPF so start with the event handler (that can be an async void).