title: Best Practices for event driven WPF UI update and Async Receive in C#?
body: <p>In an effort to learn c#, I'm writing an application that will continuously monitor UDP traffic on a particular port and update a WPF UI text block with received packet information. The following code works (UDP handler class instance <code>d</code> instantiated elsewhere in scope):</p>
  
  <pre><code>    public MainWindow()
      {
          InitializeComponent();
  
          Task.Run(async () =&gt;
          {
              using (d.receiveClient)
              {
                  while (true)
                  {
                      var receivedResults = await d.receiveClient.ReceiveAsync();
                      byte[] buffer = receivedResults.Buffer;
                      Console.Write("Receiving Data: ");
                      Console.WriteLine(buffer[0].ToString());
  
                      Dispatcher.BeginInvoke(new Action(delegate
                      {
                          MyTextBlock.Text = "Rx Data: " + buffer[0].ToString();
                      }));
                  }
              }
          });
      }
  </code></pre>
  
  <p>While it works, it's certainly doesn't feel idiomatic or correct. I'd like to create a <code>Task&lt;byte[]&gt;</code> that contains the async receive logic in the class that currently contains <code>receiveClient</code>. Problem is it doesn't execute continuously; the task will execute once, then exit. I've tried restarting the task in <code>.ContinueWith()</code>, etc, and while the Task can be restarted, I seem to loose the hooks into the UI. What's the best way to accomplish an event driven, continuous receive that in turn updates WPF UI components in native c# (I'd rather not use WinPcap or its .Net equivalent)?</p>