1.步骤1,界面
2.步骤2
只对之前Tread部分进行了修改,利用Task.Run()对一般方法进行定义任务。其余除List类型放生变化,其余和多线程一样。
namespace WpfApp1
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
tb.Visibility = Visibility.Hidden;
}
string hostname;
List<Thread> threads = new List<Thread>();
Stopwatch SumSW = new Stopwatch();
Stopwatch sw1 = new Stopwatch();
Object obj = new object();
int num = 0;
private void Button_Click(object sender, RoutedEventArgs e)
{
num = 0;
threads.Clear();
Button mybutton = sender as Button;
string strCurrent = mybutton.Content.ToString();
int n = int.Parse(t3.Text) - int.Parse(t2.Text);
if(n<0)
{
MessageBox.Show("地址范围有错");
return;
}
listbox.Items.Clear();
for (int i = 0; i <= n; i++)
{
int n2 = int.Parse(t2.Text) + i;
string lip = n2.ToString();
string strIP = t1.Text + lip;
if (strCurrent=="单线程")
{
SumSW.Start();
GetInfo(strIP);
}
else
{
Thread t = new Thread(GetInfo);
SumSW.Start();
t.Start(strIP);
threads.Add(t);
}
}
}
public void GetInfo(Object strIP)
{
string strIP2 = strIP as string;
try
{
IPAddress ip = IPAddress.Parse(strIP2);
}
catch(Exception)
{
tb.Visibility = Visibility.Visible;
}
sw1.Start();
try
{
hostname = Dns.GetHostEntry(strIP2).HostName;
}
catch (Exception)
{
hostname = "(不在线)";
}
sw1.Stop();
listbox.Dispatcher.Invoke(() =>
{
listbox.Items.Add("扫描地址:" + strIP + "扫描时间"+sw1.ElapsedMilliseconds+ "毫秒,主机DNS名称:" + hostname);
});
lock(obj)
{
num++;
}
if(num==threads.Count)
{
SumSW.Stop();
listbox.Dispatcher.Invoke(() =>
{
listbox.Items.Add("扫描总时间" + SumSW.ElapsedMilliseconds + "毫秒");
});
}
}
}
}
问题讨论:
1.方法名没加async
2.task.add加在了await前面,导致按次输出等待并导致num一直等于t.Count每次都输出总时间。删去await解决