c# - Why TcpClient.Connect is not throwing exception in async method even if it is running synchroneously -


  1. why code not throwing system.net.sockets.socketexception if no await specified? (no server listening @ specified port )
  2. why thread.sleep(4000); not executed?

    public class asynctcpclientdemos {    private static readonly ilog logger = logprovider.getcurrentclasslogger();     public async task connecttcpclientnoexception()    {        logger.debug("connecttcpclientnoexception() - start");        var tcp = new tcpclient();        tcp.connect("127.0.0.1", 9045);        thread.sleep(4000);    } } 

method called within nunit test:

[test] public void asynctcpclientnoexceptiontest() {     var asyncawait = new asynctcpclientdemos();      // todo: find out why not throwing exception     asyncawait.connecttcpclientnoexception();             } 

an async method never throws exception directly. instead, if exception raised within body of method, task returned async method becomes faulted.

the sleep isn't executed because exception does prevent rest of method executing - it's exception propagated via task instead of straight stack.

if want first part of method throw exception, can split two. example:

public task fooasync(int x, int y) {     if (x < y)     {         // thrown straight caller, in         // normal way         throw new argumentexception("...");     }     return fooasyncimpl(x, y); }  private async task fooasyncimpl(int x, int y) {     // exceptions thrown here propagated via task } 

Comments

Popular posts from this blog

How to provide Authorization & Authentication using Asp.net, C#? -

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

How to use Authorization & Authentication in Asp.net, C#? -