C# 使用任务检查internet连接
我试图执行一个后台任务,在不阻塞GUI的情况下检查internet连接(检查功能需要3秒钟来检查连接)。如果成功(或失败),面板将显示图像(根据结果显示红色或绿色) 我的代码:C# 使用任务检查internet连接,c#,multithreading,winforms,task,C#,Multithreading,Winforms,Task,我试图执行一个后台任务,在不阻塞GUI的情况下检查internet连接(检查功能需要3秒钟来检查连接)。如果成功(或失败),面板将显示图像(根据结果显示红色或绿色) 我的代码: public Image iconeConnexion; public Image IconeConnexion { get { return iconeConnexion; } set { iconeConnexion = value; } } public void myPingCompleted
public Image iconeConnexion;
public Image IconeConnexion
{
get { return iconeConnexion; }
set { iconeConnexion = value; }
}
public void myPingCompletedCallback(object sender, PingCompletedEventArgs e)
{
if (e.Cancelled || e.Error != null)
{
this.iconeConnexion = WindowsFormsApplication1.Properties.Resources.red;
return;
}
if (e.Reply.Status == IPStatus.Success)
this.iconeConnexion = WindowsFormsApplication1.Properties.Resources.green;
}
public void checkInternet()
{
Ping myPing = new Ping();
myPing.PingCompleted += new PingCompletedEventHandler(myPingCompletedCallback);
try
{
myPing.SendAsync("google.com", 3000 /*3 secs timeout*/, new byte[32], new PingOptions(64, true));
}
catch
{
}
}
加载所有控件后,我在表单中的调用加载:
Task Parent = new Task(() =>
{
checkInternet();
MessageBox.Show("Check");
});
//Start the Task
Parent.Start();
Parent.Wait();
应用程序正在运行,但到目前为止未显示任何图像。不知道为什么
你能帮我做这个吗 由于您的问题中没有太多信息,我假设当尝试从后台线程设置UI元素时,
任务
抛出并吞没了异常
由于ping服务器是一个绑定IO的操作,因此无需派生新线程。结合C#5中引入的新关键字,这可以让事情变得更简单
这是使用:
并在FormLoaded事件中调用它:
public async void FormLoaded(object sender, EventArgs e)
{
await CheckInternetAsync();
}
作为旁注:
任务
并立即等待通常意味着你做错了什么。如果这是期望的行为,那么简单地考虑同步运行该方法。任务。运行而不是新任务
。前者返回一个“热任务”(已启动的任务),而后者返回一个“冷任务”(尚未启动并等待调用Start
方法的任务)
你试过调试应用程序吗?当试图从后台线程访问UI元素时,似乎会发生异常。如果在回调函数上设置断点,它会被调用吗?它会调用函数。似乎Messagebox出现在实际调用之前。。。这就是图像不显示的原因。为什么要启动任务并立即等待它?我使用它调试任务的结束,以查看它是否可以来自任务本身。感谢您的代码,它工作正常。我根本不知道最新的关键字,这是一个很好的教训。顺便说一句,我没有FormLoaded事件,我使用了显示的事件,但它都是一样的。顺便说一句,我可以使用这样的任务在一个,比方说,10分钟的窗口上执行重复检查吗?@你确定吗,你可以在
while(true)
循环中设置它,使用wait Task.Delay(TimeSpan.frommins(10))代码>
public async void FormLoaded(object sender, EventArgs e)
{
await CheckInternetAsync();
}