我的程序:
我创建2个线程:带有侦听套接字的线程1,以及线程2执行某些操作。
但是线程1阻塞程序,直到线程1上的侦听套接字接收数据,我才能启动线程2。
但是我需要同时运行两个线程,并且不需要在两个线程之间保持同步。(但仍然在同一个程序中)。
怎么做???
我的代码是这样的:
Thread thread1 = new Thread(new ThreadStart(a.thread1));
Thread thread2 = new Thread(new ThreadStart(b.thread2));
try
{
thread1.Start();
thread2.Start();
thread1.Join(); // Join both threads with no timeout
// Run both until done.
thread2.Join();
}
答案 0 :(得分:0)
我刚刚遇到了这个同样的问题并且解决了这个问题:
private static void StartServers()
{
for (int i = Convert.ToInt32(ConfigurationManager.AppSettings.Get("PortStart"));
i <= Convert.ToInt32(ConfigurationManager.AppSettings.Get("PortEnd"));
i++)
{
var localAddr = IPAddress.Parse(ConfigurationManager.AppSettings.Get("IpAddress"));
var server = new TcpListener(localAddr, i);
Servers.Add(server);
server.Start();
StartAccept(server);
}
}
private static void StartAccept(TcpListener server)
{
server.BeginAcceptTcpClient(OnAccept, server);
}
private static void OnAccept(IAsyncResult res)
{
var client = new TcpClient();
try
{
Console.ForegroundColor = Console.ForegroundColor == ConsoleColor.Red
? ConsoleColor.Green
: ConsoleColor.White;
var server = (TcpListener) res.AsyncState;
StartAccept(server);
client = server.EndAcceptTcpClient(res);
Console.WriteLine("Connected!\n");
var bytes = new byte[512];
// Get a stream object for reading and writing
var stream = client.GetStream();
int i;
// Loop to receive all the data sent by the client.
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
var data = Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: {0} \n", data);
// Process the data sent by the client.
data = InterpretMessage(data);
var msg = Encoding.ASCII.GetBytes(data);
// Send back a response.
stream.Write(msg, 0, msg.Length);
Console.WriteLine("Sent: {0} \n", data);
}
}
catch (Exception exception)
{
Console.ForegroundColor = ConsoleColor.Red;
client.Close();
Console.WriteLine(exception.Message);
}
}
基本上这样做会创建一个异步接收系统,您可以让多个服务器同时监听多个端口。请记住,每个端口只能有一个侦听器。
在您的示例中,您只需调用StartServers方法,然后直接调用,继续执行您的应用程序正在执行的操作。
为了使其适用于单个端口上的单个服务器,只需删除StartServers中的循环并配置1个TcpListener并启动它。