简体   繁体   English

在C#/ ASP.NET中异步检查Internet

[英]Check internet asynchronously in C# / ASP.NET

My application needs a few websites to be active to work properly. 我的应用程序需要一些网站才能正常运行。 So, I want to check for websites using ping/webclient but it can take a few seconds to execute. 因此,我想使用ping / webclient检查网站,但执行过程可能需要花费几秒钟。 This code can run asynchronously but I want this code to be over before login button is clicked. 该代码可以异步运行,但是我希望在单击登录按钮之前结束该代码。

My code is: 我的代码是:

//CheckWebService method is used to check if all websites are active

public static void CheckWebService()
{
    try
    {
        WebClient WebClient = new WebClient();
        WebClient.OpenRead("https://www.website1.com");
        WebClient.OpenRead("https://www.website2.com");
        WebClient.OpenRead("https://www.website3.com");
        WebClient.OpenRead("https://www.website4.com");
    }
    catch (Exception Ex)
    {
        MessageBox.Show("Internet issues");
    }
}

//This task is made public so that I can start it in Form load event, and can wait for it to compete in my login button click event.

Task CheckWebService;

private void LoginForm_Load(object sender, EventArgs e)
{
    CheckWebService = Task.Run(() =>
        {
            CheckWebService();
        });
}

private void LoginButton_Click(object sender, EventArgs e)
{
    CheckWebService.Wait();

    //Login verification code. CheckWebService method must be complete before login code executes.
}

Am I doing this correctly? 我这样做正确吗?

You're using some pretty old tech and creating unnecessary threads. 您正在使用一些相当古老的技术并创建不必要的线程。 It's much simpler if you make your event handler async, like this: 如果使事件处理程序异步,则要简单得多,如下所示:

private async void LoginForm_Load(object sender, EventArgs e)
{
    await CheckWebService();
}

Also, HttpClient is more modern and has async methods: 另外,HttpClient更现代,并具有异步方法:

public async Task CheckWebService()
{
    try
    {
        using (var client = new HttpClient())
        {
            await client.GetAsync("https://www.website1.com");
            await client.GetAsync("https://www.website2.com");
            await client.GetAsync("https://www.website3.com");
            await client.GetAsync("https://www.website4.com");
        }
    }
    catch (HttpRequestException Ex)
    {
        MessageBox.Show("Internet issues");
    } 
}

That's the basic change. 这是基本的变化。 In addition, you may want to execute the requests in parallel, to improve response time. 另外,您可能希望并行执行请求,以缩短响应时间。 Also, you might want to check the response code from the services. 另外,您可能要检查服务中的响应代码。 Also, you should only catch the specific exceptions your code can handle; 同样,您应该只捕获代码可以处理的特定异常; if there is a system error (like out of memory) you want that to bubble up. 如果出现系统错误(例如内存不足),您希望它冒泡。

Here's how you'd do all that: 这是您要做的所有事情:

public async Task CheckWebService()
{
    bool success = false;
    try
    {
        using (var client = new HttpClient())
        {
            var tasks = new[]
            {
                client.GetAsync("http://website1.com"),
                client.GetAsync("http://website2.com"),
                client.GetAsync("http://website3.com"),
                client.GetAsync("http://website4.com"),
            };
            await Task.WhenAll(tasks);
            var results = tasks.Select(t => t.Result).ToList();
            if (results.All(r => r.StatusCode == System.Net.HttpStatusCode.OK))
            {
                success = true;
            }
        }
    }
    catch (HttpRequestException exception)
    {
    }
    if (!success) MessageBox.Show("Error");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM