1

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 ?

tweetysat
  • 2,187
  • 14
  • 38
  • 75

1 Answers1

1

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

Sebastian Negraszus
  • 11,915
  • 7
  • 43
  • 70
  • Ok, thanks. I tried with await Task.Run(()=>{waitPacket()}); and public void waitPacket(){ ... }. It's working. But in the Tasks_Button_Click, no matters if I put await Task.WhenAll(myTask); the Console.WriteLine("...."); only happens when the waitPacket is finished. I'd like to try the other method (ReceiveFromAsync) if I found examples. – tweetysat Jan 20 '14 at 15:04
  • Note the `Task.Run(` version is just your thread version "pretttyfied" it still has the same problems with scaling. See the example that was linked to in your question http://stackoverflow.com/questions/21013751/what-is-the-async-await-equivalent-of-a-threadpool-server/21018042#21018042 – Scott Chamberlain Jan 20 '14 at 15:12
  • Ok,so using threads and Task.Run it is the same. The 'look' is different but the result is the same. It is right ? And indeed using this solution, it's impossible to update ui within the task. So what would be the solution ? – tweetysat Jan 21 '14 at 07:07
  • Don't find examples with ReceiveFromAsync. – tweetysat Jan 21 '14 at 07:39