这样一段代码,网上看见的,说是可以新来一个请求就新建一个线程,有点疑问。
private void StartListening()
{
listener = new TcpListener(listenport);
listener.Start();
while (true)
{
try
{
Socket s = listener.AcceptSocket();
clientsocket = s;
clientservice = new Thread(new ThreadStart(ServiceClient));
clientservice.Start();
}
catch(Exception e)
{
Console.WriteLine(e.ToString() );
}
}
}
比如当客户a发来请求,建立一个线程,如果a的ServiceClient还没有执行完毕,b发送请求了,那么是不是a的线程就结束了?如果是这样,那怎么才能真正实现一个客户一个线程?
private void StartListening()
{
listener = new TcpListener(listenport);
listener.Start();
while (true)
{
try
{
Socket s = listener.AcceptSocket();
clientsocket = s;
clientservice = new Thread(new ThreadStart(ServiceClient));
clientservice.Start();
}
catch(Exception e)
{
Console.WriteLine(e.ToString() );
}
}
}
比如当客户a发来请求,建立一个线程,如果a的ServiceClient还没有执行完毕,b发送请求了,那么是不是a的线程就结束了?如果是这样,那怎么才能真正实现一个客户一个线程?
这就好比你打开一个notepad, 接着再打开一个notepad, 第一个notepad并不会结束。
class Program
{
static Thread th;
static void Main(string[] args)
{
StreamWriter sw = new StreamWriter(@"c:\1.txt");
while (true)
{
th = new Thread(new ThreadStart(th1));
th.Start();
Console.WriteLine("你好"+th.ManagedThreadId);
sw.Write(th.ManagedThreadId.ToString());
}
}
public static void th1()
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i); }
}
}
下面是部分执行结果:
8
9
你好216
0
1
2
3
4
5
6
7
8
9
0
1
2
3
4
5
6
7
8
9
你好217
你好218
0
1
2
3
4
5
6
7
8
9
你好219
0
1
2
3
4
5
6
7
8
9
0
1
2
3
4
5
6
7
8
9
你好220
你好221
0
1
2
3
4
5
6
7
8
9
你好222
0
1
2
3
4
5
6
看这个结果感觉是一个执行完了才执行下个线程
i=11;
如果这样写的话等于后面的11把前面的10给替换掉了,那对于对象呢?
x=new a(10);
x=new a(11);
第一个x是不是没有起作用?以后用的时候都是用的第二个x的定义?这两个x是相互独立的吗?
对于线程呢?
th = new Thread(new ThreadStart(th1));
th = new Thread(new ThreadStart(th1));
我现在似懂非懂,头晕,好像有点钻牛角尖了
--------------------
x=new a(10) --> a(10) 的地址
--------------------
--------------------
x=new a(11) --> a(11) 的地址
--------------------