private static void Main(string[] args)
{
for (int i = 0; i < 10; i++)
{
Thread t = new Thread(test1);
t.Start(i);
}
}
--------------------------------------------------------
public static void test1(object obj)
{
int i = (int)obj;
string url_path = string.Empty;
try
{
url_path = "http://localhost:888/Test";
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url_path);
using (HttpWebResponse response = (HttpWebResponse)httpWebRequest.GetResponse())
{
var encoding = ASCIIEncoding.UTF8;
using (var reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
{
Console.WriteLine("{"+i+"}"+reader.ReadToEnd());
}
}
}
catch (System.Exception ex)
{
Console.WriteLine("异常:" + ex.Message);
}
}
如上没问题
但是单元测试中就报错:
[TestMethod]
public void HttpListenerTest()
{
for (int i = 0; i < 1; i++)
{
Thread t = new Thread(test1);
t.Start(i);
}
}
异常信息:
加个Semaphore/CountdownEvent去控制下,在最后去wait所有线程结束,否则你test方法会很快执行完而你的这些线程还在运行。