前一章学习了IAsyncResult结果分析,在要得到结果时往往会阻塞当前线程,这对于用户体验,尤其是CS端客户非常不友好,容易造成界面卡死的现象.
怎么解决呢?
红色字体是关键
既然你阻塞的是当前线程,那我再Button_Click事件里面再重启一个新的线程执行相应的方法,但要注意一些需要同步是数据
两种方案,以前一章的例子为例:
第一种直接启动一个新线程:
ThreadStart start = delegate()
{
IAsyncResult result = Dns.BeginGetHostEntry("192.168.1.1", null, null);
Console.WriteLine("Processing your request for information...");
try
{
IPHostEntry host = Dns.EndGetHostEntry(result);
string[] aliases = host.Aliases;
IPAddress[] address = host.AddressList;
if (aliases.Length > 0)
{
Console.WriteLine("Aliases");
for (int i = 0; i < aliases.Length; i++)
{
Console.WriteLine(" {0} ", aliases[i]);
}
}
if (address.Length > 0)
{
Console.WriteLine("Addresses");
for (int i = 0; i < address.Length; i++)
{
Console.WriteLine(" {0} ", address[i].ToString());
}
}
}
catch (SocketException ex)
{
Console.WriteLine("An exception occurred while processing the request: {0}", ex.Message);
}
};
Thread thread = new Thread(start);
thread.Start();
第二种,采用线程池来启动一个新线程(推荐):
ThreadPool.QueueUserWorkItem(delegate(object obj) {
IAsyncResult result = Dns.BeginGetHostEntry("192.168.1.1", null, null);
Console.WriteLine("Processing your request for information...");
try
{
IPHostEntry host = Dns.EndGetHostEntry(result);
string[] aliases = host.Aliases;
IPAddress[] address = host.AddressList;
if (aliases.Length > 0)
{
Console.WriteLine("Aliases");
for (int i = 0; i < aliases.Length; i++)
{
Console.WriteLine(" {0} ", aliases[i]);
}
}
if (address.Length > 0)
{
Console.WriteLine("Addresses");
for (int i = 0; i < address.Length; i++)
{
Console.WriteLine(" {0} ", address[i].ToString());
}
}
}
catch (SocketException ex)
{
Console.WriteLine("An exception occurred while processing the request: {0}", ex.Message);
}
},1);
为什么?
看这里:
设置可以同时处于活动状态的线程池的请求数目。 所有大于此数目的请求将保持排队状态,直到线程池线程变为可用。第一个方法
发出新的请求时,在切换到管理线程创建和销毁的算法之前设置线程池按需创建的线程的最小数量。第二个方法
ThreadPool.SetMaxThreads(5, 3);
ThreadPool.SetMinThreads(0, 0);
可以根据服务器和业务需要设定最大值,最小值,让系统管理,简单,安全.