110,571
社区成员
发帖
与我相关
我的任务
分享
ThreadPool.QueueUserWorkItem(h => tsk.Send());
来开始Send过程,瞬间之后,线程就释放给系统线程池了(而不是一直卡在那里),直到 BeginWrite 方法所注册的(匿名委托)回调方法被系统I/O线程执行的时候,才会再去瞬间又使用线程池中的线程。
由于使用了异步Write,所以并不死等。就算你并发发送100个大文件,那么也不会占用100个线程,或许有5个也就够了,因为大多数时间都是在等待异步回调,而不是让一堆线程卡在那里。public class SendTask
{
public Stream InputStream;
public NetworkStream OutputStream;
public int Length;
public int SendPosition { private set; get; }
public bool PauseFlag;
private byte[] buffer = new byte[4000000];
public void Send()
{
if (SendPosition < Length)
{
if (InputStream.Position != SendPosition)
InputStream.Position = SendPosition;
var len = InputStream.Read(buffer, 0, buffer.Length);
if (len > 0)
{
OutputStream.BeginWrite(buffer, 0, len, x =>
{
OutputStream.EndWrite(x);
SendPosition += len;
if (SendPart != null)
SendPart();
if (!PauseFlag)
Send();
}, null);
}
}
}
public event Action SendPart;
}
while(isStop)
{
//做你想做的事情
}