Is a non-blocking, single-threaded, asynchronous w

2019-01-29 22:04发布

I was looking at this question, looking for a way to create a single-threaded, event-based nonblocking asynchronous web server in .NET.

This answer looked promising at first, by claiming that the body of the code runs in a single thread.

However, I tested this in 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);
    }
}

And the result was:

1
5

So it seems like, contrary to the answer, the thread initiating the read and the thread ending the read are not the same.

So now my question is, how do you to achieve a single-threaded, event-based nonblocking asynchronous web server in .NET?

13条回答
【Aperson】
2楼-- · 2019-01-29 22:37

I've been fiddling with my own simple implementation of such an architecture and I've put it up on github. I'm doing it more as a learning thing. But it's been a lot of fun and I think I'll flush it out more.

It's very alpha, so it's liable to change, but the code looks a little like this:

   //Start the event loop.
   EventLoop.Start(() => {

      //Create a Hello World server on port 1337.
      Server.Create((req, res) => {
         res.Write("<h1>Hello World</h1>");
      }).Listen("http://*:1337");

   });

More information about it can be found here.

查看更多
登录 后发表回答