websocket-sharp icon indicating copy to clipboard operation
websocket-sharp copied to clipboard

Concurrent request error in HttpServer

Open yejinmo opened this issue 3 years ago • 0 comments

Describe the bug

test code:

static void Main(string[] args)
{
    ThreadPool.SetMinThreads(127, 127);
    HttpServer httpServer = new HttpServer(10100);
    httpServer.OnGet += (sender, e) =>
    {
        var url = e.Request.Url.PathAndQuery;
        var data = Encoding.ASCII.GetBytes(url);
        e.Response.StatusCode = 200;
        e.Response.ContentLength64 = data.Length;
        e.Response.OutputStream.Write(data, 0, data.Length);
    };
    httpServer.Start();
    var httpClient = new HttpClient();
    var maxThreads = 2;
    var maxGroups = 2;
    for (int j = 1; j <= maxGroups; j++)
    {
        var group = j;
        for (int i = 1; i <= maxThreads; i++)
        {
            var thread = i;
            Task.Run(() =>
            {
                Console.WriteLine($"Group {group} Thread {thread} Start");
                while (true)
                {
                    var baseUrl = "http://127.0.0.1:10100";
                    var url = $"/{group}";
                    var response = httpClient.GetAsync(baseUrl + url).Result;
                    var content = response.Content.ReadAsStringAsync().Result;
                    if (content != url)
                    {
                        Console.WriteLine($"error: {url} != {content}");
                    }
                }
            });
        }
    }
    new AutoResetEvent(false).WaitOne();
}

Expected Behavior

Console.WriteLine($"error: {url} != {content}"); never run

But

console output:

Group 1 Thread 1 Start
Group 1 Thread 2 Start
Group 2 Thread 2 Start
Group 2 Thread 1 Start
error: /2 != /1
error: /1 != /2
error: /2 != /1
error: /1 != /2
error: /2 != /1
error: /1 != /2
error: /2 != /1
error: /1 != /2
error: /2 != /1
error: /1 != /2
error: /2 != /1
error: /2 != /1
error: /1 != /2
error: /1 != /2
error: /2 != /1
error: /1 != /2

.NET Version

.Net Framework 4.6.1

Anything else?

I started the IIS server and put two files to test, everything works fine, there is no problem with HttpClient .

yejinmo avatar Jan 19 '22 09:01 yejinmo