C# How to start an async method without await its complete?

前端 未结 6 1447
醉酒成梦
醉酒成梦 2021-02-05 08:12

Sometimes I need to start an async job which works very slow. I don\'t care if that job success and I need to continue working on my current thread.

Like sometimes I nee

6条回答
  •  南笙
    南笙 (楼主)
    2021-02-05 08:28

    It all depends on what your Async method accepts. Normally it will accept a "special" class that also holds an event. You can subscribe your callback method to that event and pass it along with the method. When it's finished, your callback method will be called.

    An example of this (for sockets) would be:

        public void CreateSocket()
        {
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            SocketAsyncEventArgs sockAsync = new SocketAsyncEventArgs();
            sockAsync.Completed += SockAsync_Completed;
    
            s.ConnectAsync(sockAsync);
        }
    
        private void SockAsync_Completed(object sender, SocketAsyncEventArgs e)
        {
            //Do stuff with your callback object.
        }
    

    It all depends on what the method you are trying to call can accept. I would look at the documentation for more help on that specifically.

提交回复
热议问题