質問

while ago I was looking for some realiable way of checking internet connection, at same time i would like it not to render my aplication irresponsive, I found various examples like this code:

public static bool CheckForInternetConnection()
    {
        try
        {
            using (var client = new WebClient())
                using (var stream = client.OpenRead("http://www.google.com"))
                {
                    return true;
                }
        }
        catch
        {
            return false;
        }
    }

That use WebClient, but main flaw of these solutions is fact they freeze entire application, and since I do connection tests every few minutes this behaviour is highly unwanted.

What i want to achieve is to get that piece of code working in a way it will execute but it will keep application waiting for response and at the same time it wont make UI irresponsive.

Cheers MTH

EDIT:

I want to be for this code to be avaliable form multiple code paths, preferably as static method of some static class. Doing it as background worker does limit it in a way. I will try with separate thread, and see if it will bring effect that i want to achieve.

I just want to get all what happens during call of that simple method above(delay, all other operations waiting for method to fisnish), just without blocking UI, so while connection is checked app is waiting but doesn't hang

役に立ちましたか?

解決

If you can't use a BackgroundWorker and you're targeting .NET 4.5 you can wrap that method inside a Task.

public static Task<bool> CheckInternetConnectionAsync( )
        {
            return Task<bool>.Run( ( ) => {
                try
                {
                    using ( var client = new WebClient( ) )
                    using ( var stream = client.OpenRead( "http://www.google.com" ) )
                    {
                        return true;
                    }
                }
                catch
                {
                    return false;
                }
            } );
        }

And whenever you need to check for internet connection do it like this ...

static async void CheckInternetConnection( )
        {
//just an example how to read a value from Task
            bool hasConnection = await CheckInternetConnectionAsync( );
        }

他のヒント

You need to use multithreading to run the check on another thread so it does not interfere with your main application.

Thread thread = new Thread(() => ConnectionCheck());
thread.Start();
...
public static void ConnectionCheck()
{
     bool result = CheckForInternetConnection();
     //Do something with result
}

In your case it might be easier to use a BackgroundWorker to use your return value easier. You can run a task, store the output in the Result variable and use it when completed.

BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
worker.RunWorkerAsync("Name");

void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    bool result = (bool)e.Result;
    //Do something with Result
}

void worker_DoWork(object sender, DoWorkEventArgs e)
{
   e.Result = CheckForInternetConnection();
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top