1

In c#, I have a device that accepts HTTP requests as remote commands.

I've created a button that send those requests, it's not the perfect but it works.

However, when the device is disconnected and there is

destination unreachable

response the application freezes until i restarts it. I need a way around it, maybe some timeout that will close the stream after 1 second.

     private void httpBTN_Click(object sender, EventArgs e)
    {
        String URI = "http://192.168.1.118/cgi-bin/aw_cam?cmd=DCB:0&res=0";
        WebClient webClient = new WebClient();
        Stream stream = webClient.OpenRead(URI);
        stream.Close();
    }
jazb
  • 5,498
  • 6
  • 37
  • 44
  • Please check this [question](https://stackoverflow.com/questions/1789627/how-to-change-the-timeout-on-a-net-webclient-object). – kennyzx Nov 06 '18 at 05:20
  • 2
    Possible duplicate of [How to return async HttpClient responses back to WinForm?](https://stackoverflow.com/questions/45089300/how-to-return-async-httpclient-responses-back-to-winform) – mjwills Nov 06 '18 at 05:22
  • Also, consider using OpenReadAsync instead of OpenRead, `OpenReadAsync` doesn't block the UI so the app remains responsive while it is waiting for the web response. – kennyzx Nov 06 '18 at 05:24

1 Answers1

0

Long running operations in GUI's are propblem: As long as the operation has not finished (result or timeout), the event does not finish. And as long as a Event does not finish, no other code can run. Not even the code that updates the GUI with changes or "yes, I got the message about a user input" to Windows. You will need some form of Multitasking.

Luckily Networking is one of the most common cases of long running Operations, so it has build-in ways of multitasking (the async functions). However that might no be the best start. As Multitasking beginner I would advise towards using the BackgroundWorker in Windows Forms. At least until you got a handle on Invoke and Race Conditions. async/await is the better pattern longterm, but has a much steeper learning curve.

Christopher
  • 9,634
  • 2
  • 17
  • 31