C# NetWork Programming里面一个例子,通过异步的方式解析域名。主要是应用Dns类的BeginResolve(),和EndResolve()方法。此例子有一个问题就是当碰到解析不出来的域名时,不会调用AsyncCallback指定的函数。我加了几句代码,设定2秒钟超时时间,超时的话,显示超时。现在的问题是,超时后并没有结束域名的解析。超过2秒钟解析出的域名还会显示到listBox中。而超时后想调用Dns.EndResolve()结束解析的话会抛出异常。
有待研究。
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Net;
using System.Threading;
namespace NetWork
{
public class DnsResolver : System.Windows.Forms.Form
{
private System.Windows.Forms.Button btnResolve;
private System.Windows.Forms.Button btnClear;
private System.Windows.Forms.Button btnAbout;
private System.Windows.Forms.ListBox lbResults;
private System.Windows.Forms.TextBox txtHost;
private System.ComponentModel.Container components = null;
public DnsResolver()
{
InitializeComponent();
}
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.btnResolve = new System.Windows.Forms.Button();
this.txtHost = new System.Windows.Forms.TextBox();
this.lbResults = new System.Windows.Forms.ListBox();
this.btnClear = new System.Windows.Forms.Button();
this.btnAbout = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// btnResolve
//
this.btnResolve.Location = new System.Drawing.Point(24, 64);
this.btnResolve.Name = "btnResolve";
this.btnResolve.TabIndex = 0;
this.btnResolve.Text = "&Resolve";
this.btnResolve.Click += new System.EventHandler(this.btnResolve_Click);
//
// txtHost
//
this.txtHost.Location = new System.Drawing.Point(8, 24);
this.txtHost.Name = "txtHost";
this.txtHost.Size = new System.Drawing.Size(160, 21);
this.txtHost.TabIndex = 1;
this.txtHost.Text = "";
//
// lbResults
//
this.lbResults.ItemHeight = 12;
this.lbResults.Location = new System.Drawing.Point(176, 8);
this.lbResults.Name = "lbResults";
this.lbResults.Size = new System.Drawing.Size(296, 232);
this.lbResults.TabIndex = 2;
//
// btnClear
//
this.btnClear.Location = new System.Drawing.Point(24, 112);
this.btnClear.Name = "btnClear";
this.btnClear.TabIndex = 3;
this.btnClear.Text = "&Clear";
this.btnClear.Click += new System.EventHandler(this.btnClear_Click);
//
// btnAbout
//
this.btnAbout.Location = new System.Drawing.Point(24, 160);
this.btnAbout.Name = "btnAbout";
this.btnAbout.TabIndex = 4;
this.btnAbout.Text = "&About...";
this.btnAbout.Click += new System.EventHandler(this.btnAbout_Click);
//
// DnsResolver
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(504, 253);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.btnAbout,
this.btnClear,
this.lbResults,
this.txtHost,
this