0

I'm studying c# and tried other solutions that I've found on stackoverflow.. But I failed..

I'm trying to check if an URL exists when click a button.

When the button is clicked, a progressBar is set to marquee and the verification begins.

But the system stops until the result backs..

Here is the button click:

private void button1_Click(object sender, EventArgs e)
{

   this.progressBar1.Style = System.Windows.Forms.ProgressBarStyle.Marquee;

   if (RemoteFileExists("http://www.gofdisodfi.com/"))
   {
      // OK
   }
   else
   {
      //FAIL
   }
}

And here is the check:

private bool RemoteFileExists(string url)
{
   try
   {
      HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
      request.Method = "HEAD";
      HttpWebResponse response = request.GetResponse() as HttpWebResponse;
      return (response.StatusCode == HttpStatusCode.OK);
   }
   catch
   {
      return false;
   }
}
user3787036
  • 191
  • 10
  • Note that title of you post talks about async requests, but no asynchronous code is shown in the sample. Would you mind clarifying what exact problem you have (likely should be duplicate of either something like "async request in C#" or "why UI freezes during long running operations"). – Alexei Levenkov Jan 15 '15 at 03:32
  • Thanks for edit - I think this is asked several times in the past. Check out duplicate - feel free to comment if you think duplicate *does not* cover your case. Also make sure to look through "Related" posts showing multiple ways to make async calls. – Alexei Levenkov Jan 15 '15 at 03:41

1 Answers1

1

You could use the "async and await" syntax for asynchronous action. It won't freeze the UI

private async void button1_Click(object sender, EventArgs e)
    {
        this.progressBar1.Style = System.Windows.Forms.ProgressBarStyle.Marquee;

        var result = await RemoteFileExists("http://www.google.com/");

        if (result)
        {
            // OK
            MessageBox.Show("OK");
        }
        else
        {
            //FAIL
            MessageBox.Show("Fail");
        }
    }

    private async Task<bool> RemoteFileExists(string url)
    {
        try
        {
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "HEAD";
            HttpWebResponse response = await request.GetResponseAsync() as HttpWebResponse;
            return (response.StatusCode == HttpStatusCode.OK);
        }
        catch
        {
            return false;
        }
    }

You can read more about it here: http://blog.stephencleary.com/2012/02/async-and-await.html

Huy Hoang Pham
  • 4,107
  • 1
  • 16
  • 28