简体   繁体   中英

C# .net 4.5 - Asynchronous task & socket

Next step in my discovery of .net.

At the beginning I was using threads. After a discussion on another question (thanks ledbutter) I'm now using tasks.

So I have :

   private async void Tasks_Button_Click(object sender, RoutedEventArgs e)
    {
        Task myTask = doSomething();
        await Task.WhenAll(myTask);
        Console.WriteLine("....");
    }
    private async Task doSomething()
    {
        Console.WriteLine("Starting doSomething3");
        await Task.Delay(3000);
        Console.WriteLine("Finishing doSomething3");
    }

Now in my doSomething I want to use sockets to listen to a specified port. In my version with threads, I was doing :

Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 5000);
sock.Bind(iep);
EndPoint ep = (EndPoint)iep;
Console.WriteLine("Ready to receive...");
byte[] data = new byte[1024];
int recv = sock.ReceiveFrom(data, ref ep);
string stringData = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine("received: {0}  from: {1}", stringData, ep.ToString());
sock.Close();

But if put put this code in the doSomething method, the RreceiveForm block the ui thread and all other tasks.

How can I do ?

Your network code does not await anything, so it does not run asynchronously. Either use the asynchronous operations of the Socket class, eg await sock.ReceiveFromAsync(...); , or run the code as a Task, eg await Task.Run(()=>{/*your code here*/});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM