开发者

c# app that close self on start if there's no internet connection

开发者 https://www.devze.com 2023-02-11 06:19 出处:网络
if(IsConnected() == false) { Console.WriteLine(\"no connection\"); System.Windows.Forms.开发者_开发技巧Application.Exit();
if(IsConnected() == false)
{
    Console.WriteLine("no connection");
    System.Windows.Forms.开发者_开发技巧Application.Exit();
}

InitializeComponent();

...

public static bool IsConnected()
{
    System.Uri Url = new System.Uri("http://google.com");

    System.Net.WebRequest WebReq;
    System.Net.WebResponse Resp;
    WebReq = System.Net.WebRequest.Create(Url);            

    try
    {
        Resp = WebReq.GetResponse();
        Resp.Close();
        WebReq = null;
        return true;
    }

    catch
    {
        WebReq = null;
        return false;
    }
}

Here's part of code (c# .net 1.0) which check if there is connection or not and depending on that i want my app to close (exit) I can see in console log that there is "no connection" but app keep running... How to exit that app properly there?


public static bool IsConnected()
{
  HttpWebRequest HttpWReq = (HttpWebRequest)WebRequest.Create("http://www.google.com");

  HttpWebResponse HttpWResp = (HttpWebResponse)HttpWReq.GetResponse();
  bool isconnected = (HttpWResp.StatusCode == HttpStatusCode.OK);
  HttpWResp.Close();
  return isconnected;
}


If you're writing a console application, you just need it to return from its Main method (and not have any non-background threads running). Application.Exit only performs work against windows forms applications, and even then, doesn't cause the application to actually exit:

The Exit method stops all running message loops on all threads and closes all windows of the application. This method does not necessarily force the application to exit

if you are writing a windows forms application, (and you have a main method) then you need to investigate what your code is doing after the call to Application.Run, which is where the message loop is running - this call is returned from when the message loop stops.

But consider this - what if you're internet check succeeds, but the user's internet connection drops immediately afterwards (and before you do any useful work).

Or the check fails due to an intermittent connection, but is immediately available again afterwards.

Wouldn't your time be better spent with dealing with intermittent connections, and working on a best effort basis for your users? You're going to have to deal with these issues anyway, why give the user reasons to delete your application?

0

精彩评论

暂无评论...
验证码 换一张
取 消