我当时在看this question,想找一种方法来创建一个single-threaded,基于事件的非阻塞异步web服务器.网
This answer一开始看起来很有希望,因为它声称代码体在一个线程中运行.
然而,我在C#中测试了这一点:
using System;
using System.IO;
using System.Threading;
class Program
{
static void Main()
{
Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
var sc = new SynchronizationContext();
SynchronizationContext.SetSynchronizationContext(sc);
{
var path = Environment.ExpandEnvironmentVariables(
@"%SystemRoot%\Notepad.exe");
var fs = new FileStream(path, FileMode.Open,
FileAccess.Read, FileShare.ReadWrite, 1024 * 4, true);
var bytes = new byte[1024];
fs.BeginRead(bytes, 0, bytes.Length, ar =>
{
sc.Post(dummy =>
{
var res = fs.EndRead(ar);
// Are we in the same thread?
Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
}, null);
}, null);
}
Thread.Sleep(100);
}
}
结果是:
1
所以看起来,与答案相反,启动读取的线程和结束读取的线程是相同的.
现在我的问题是,如何在中实现single-threaded个基于事件的非阻塞异步web服务器.网