技术开发 频道

利用BackgroundWorker检测网络连接

  好了,我们开始创建我们的检测组件。

  首先我们创建一个Windows Form Application,然后添加一个组件,这些过程不再详述。我们将新建的组件命名为InternetConnection,我们先定义两个私有字段BackgroundWorker类型的bgworker和string类型的reliableURL。然后定义两个属性:
 

public string ReliableURL
        {
            
get { return reliableURL; }
            
set { reliableURL = value; }
        }

        
public bool Active
        {
            
set
            {
                
if (value == true)
                {
                    bgworker.RunWorkerAsync();
                }
                
else
                {
                    bgworker.CancelAsync();
                }
            }
        }

  ReliableURL属性就是我们前述的所谓远程地址,我们通过访问一个可靠地址或者我们自己的WebService地址来间接检测Internet连接是否可用。Active属性允许控制BackgroundWorker的异步执行状态,通过设置该组件Active属性为true来启动后台Internet连接检测。

  接下来就需要定义事件了。简单起见我们为这个组件定义了两个事件,Connected和ConnectFailure,前者是连接成功后激发的事件,后者是连接失败激发的事件。我们事件不需要参数传递,更多关于事件的叙述请参考我的另一篇博文:.Net事件与委托

public event EventHandler Connected;
public event EventHandler ConnectFailure;

        
protected virtual void OnConnected(EventArgs e)
        {
            
if (Connected != null)
            {
                Connected(
this, e);
            }
        }

        
protected virtual void OnConnectFailure(EventArgs e)
        {
            
if (ConnectFailure != null)
            {
                ConnectFailure(
this, e);
            }
        }

 
0
相关文章