using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Runtime.Remoting.Contexts;[Synchronization()] class A: ContextBoundObject { public void Method1() { string threadName = Thread.CurrentThread.Name; Console.WriteLine(threadName + ": Method1 started"); Thread.Sleep(3000); Console.WriteLine(threadName + ": Method1 finished"); } } class Tests { A obj = new A(); public void ThreadMethod() { obj.Method1(); } static void Main(string[] args) { Tests test = new Tests(); //create and start a thread Thread t1 = new Thread(new ThreadStart(test.ThreadMethod)); t1.Name = "Thread 2"; t1.Start(); //invoke Method1 with the main thread Thread.CurrentThread.Name = "Thread 1"; test.obj.Method1(); t1.Join(); } }
完成端口的细节你可以不需要考虑只要你尽量使用Socket.BeginXxx来编写Socket程序,就能让你的服务器程序达到最大的网络处理量.不过说起来,DotNet的Socket编程真的很费内存.
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Runtime.Remoting.Contexts;[Synchronization()]
class A: ContextBoundObject
{
public void Method1()
{
string threadName = Thread.CurrentThread.Name;
Console.WriteLine(threadName + ": Method1 started");
Thread.Sleep(3000);
Console.WriteLine(threadName + ": Method1 finished");
}
}
class Tests
{
A obj = new A(); public void ThreadMethod()
{
obj.Method1();
} static void Main(string[] args)
{
Tests test = new Tests(); //create and start a thread Thread t1 = new Thread(new ThreadStart(test.ThreadMethod));
t1.Name = "Thread 2";
t1.Start(); //invoke Method1 with the main thread
Thread.CurrentThread.Name = "Thread 1";
test.obj.Method1();
t1.Join(); }
}
BeginXXX/EndXXX.它的好处是可最大限度地利用通讯硬件自己的线程和资源,而不是CPU上的线程. 比如用TcpClient类作异步读时,可以用TcpClient.GetStream().BeginRead, 并在它的CallBack函数中再次调用BeginRead,从而形成一个循环. 2. 线程对Server程序来说是非常昂贵的资源,尽量从设计的时候就少开线程,如果一个程序同时有二三百个线程,它即使不死性能也会很差. 楼主这个系统,如果服务器解析每个用户线程发来的消息时需要使用一些线程之间的共享资源和数据,为减少线程同步的开销和复杂性,可以考虑接到用户消息后马上抛到一个临时队列里,整个程序只用一个线程从队列中取出消息并解析.假如处理了客户端的信息后还需要向客户端返回信息,可以采用异步方式发送,这样一来服务器性能会好一些.
3.如果需要向控制端发送许多一模一样的信息而且控制端都在同一个网段里,可以考虑用UDP的MultiCast来减少点儿负担,前提是所在的网允许MultiCast.