3

인터넷 연결이 필요한 몇 가지 기능을 수행하는 Windows Store App을 만들려고합니다. 내 코드는 인터넷 연결이없는 경우에만 임시 SQLite DB에 데이터를 저장하여 인터넷 연결을 처리하지 않습니다. 다음과 같은 것 :C#에서 좋은 인터넷 연결이 있는지 확인하는 방법은 무엇입니까?

// C# 
    public bool isInternetConnected() 
    { 

     ConnectionProfile conn = NetworkInformation.GetInternetConnectionProfile(); 
     bool isInternet = conn != null && conn.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess; 
     return isInternet; 
    } 

이제 내 문제는 잘못된 인터넷 연결이있는 것입니다. 내 작업이 시간 초과됩니다. 시간 초과를 처리하거나이 방법을 수정해야합니다.

아무도이 문제를 처리 할 수있는 좋은 방법이 있습니까?

답변

1

이 시도 : 를 결과가 120 ~ 40 사이는, 대기 시간이 좋은, 그리고 연결이 좋은 경우 :

사용법 :

PingTimeAverage("stackoverflow.com", 4); 

구현 :

public static double PingTimeAverage(string host, int echoNum) 
{ 
    long totalTime = 0; 
    int timeout = 120; 
    Ping pingSender = new Ping(); 

    for (int i = 0; i < echoNum; i++) 
    { 
     PingReply reply = pingSender.Send (host, timeout); 
     if (reply.Status == IPStatus.Success) 
     { 
      totalTime += reply.RoundtripTime; 
     } 
    } 
    return totalTime/echoNum; 
} 
0

예외가있는 try 문을 사용하는 경우 인터넷 연결이 없을 때 작업을 처리 할 수 ​​있어야합니다. 인터넷 연결이없는 것은 예외 일 수 있습니다.

try 
{ 
    // Do not initialize this variable here. 
} 
catch 
{ 
} 

이 경우 try-catch를 사용하면 인터넷이 중단되는 경우 처리하는 데 가장 효율적인 방법이 될 것 같습니다.

0

이것을 시도해보고 반복적으로 여러 테스트 URI를 호출 할 수 있습니다.

public static async Task<bool> CheckIfWebConnectionIsGoodAsync(TimeSpan? minResponseTime, Uri testUri) 
{ 
    if (minResponseTime == null) 
    { 
     minResponseTime = TimeSpan.FromSeconds(0.3); 
    } 

    if (testUri == null) 
    { 
     testUri = new Uri("http://www.google.com"); 
    } 

    var client = new HttpClient(); 
    var cts = new CancellationTokenSource(minResponseTime.Value); 

    try 
    { 
     var task = client.GetAsync(testUri).AsTask(cts.Token); 
     await task; 
     if (task.IsCanceled) 
      return false; 
     return true; 
    } 
    catch (Exception) 
    { 
     return false; 
    } 
}