title: c# ping machine in async way
body: <p>I'm working on a legacy application which communicates against an external machine and the communication is made thru file. Basically machine A writes a file, B get it and reply with another file.
  Currently all works fine but I have a code which is called every 5 seconds that checks if the remote directory (where the files are written) exists or not. Tihs is the code:</p>
  
  <pre><code>private delegate bool DirectoryExistsDelegate(string folder);
      public static bool DirectoryExists(string path, int timeout = 2000)
      {
          Func&lt;bool&gt; func = () =&gt; Directory.Exists(path);
          Task&lt;bool&gt; task = new Task&lt;bool&gt;(func);
          task.Start();
          return task.Wait(timeout) &amp;&amp; task.Result;
      }
  </code></pre>
  
  <p>It seems that the method above freeze the UI, particularly when we're using a network share, such <strong>\\10.100.100.1\sharedFolder</strong>
  So I thought to ping the host before try to access:</p>
  
  <pre><code>private static IPStatus PingStatus;
      public static async void PingIP(string IPaddress, int timeout = 2000)
      {
          // Verifica indirizzo IP
          if (string.IsNullOrEmpty(IPaddress)) return;
          Ping s = new Ping();
          PingStatus = await s.SendPingAsync(IPaddress, timeout).ContinueWith(pingTask =&gt; pingTask.Result.Status);
      }
  
      private delegate bool DirectoryExistsDelegate(string folder);
      public static bool DirectoryExists(string path, int timeout = 2000)
      {            
          if (path.StartsWith("\\"))
          {
              string[] address = path.Split('\\');
              PingIP(address[2], timeout);
  
              if (PingStatus != IPStatus.Success) return false;
          }
  
          Func&lt;bool&gt; func = () =&gt; Directory.Exists(path);
          Task&lt;bool&gt; task = new Task&lt;bool&gt;(func);
          task.Start();
          return task.Wait(timeout) &amp;&amp; task.Result;
      }
  </code></pre>
  
  <p>I call the main method as:</p>
  
  <pre><code>    if (!Uti.DirectoryExists(PathCom.Value, 5000))
          return false;       
  </code></pre>
  
  <p>I dunno if the idea is correct or not, but is logically right I guess. The problem is that the PingStatus return always True (at first call), event the server does not exists, since the second seems work fine.
  How th let SendPingAsync await the ping result and not freeze the UI?</p>