Evžen Křídlo
Evžen Křídlo

Reputation: 37

Catching async operation exception is not working

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

Upvotes: 0

Views: 413

Answers (1)

bommelding
bommelding

Reputation: 3037

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).

Upvotes: 2

Related Questions