Search code examples
c#.netazuremultithreadingasp.net-core-mvc

Threading MVC 6 .net 5


I have developed an API where I am handling requests that redirect to multiple databases.

It has been working fine, but have recently hit a road block. I have been googling for two days and trying several different solution but they all do not seem to work.

My application is handling requests on a FIFO basis.

[HttpGet("getList")]
public string Get(string token, string page, string amount) {
    string value = null;
    var thread = new Thread(
      () => {
          value = CustomerDA.getList(token, page, amount);
    });
    thread.Start();
    thread.Join();
    return value;
}

This is the most up to date solution that I have tried... I need to return a string back to client based on what they pass into this method call. I am confused because I thought that this technology handled these requests asynchronously by default.

Here is another attempt:

[HttpGet("getList")]
public async Task<string> Get(string token, string page, string amount) {
    var t = Task<int>.Run(() => {
        return CustomerDA.getList(token, page, amount);
    });
    return t.Result;
}

Solution

  • In the second attempt you create a Task (= Thread) and then immediately wait synchronously for it to finish. If you want to wait asynchronously, you have to use await.

    [HttpGet("getList")]
    public async Task<string> Get(string token, string page, string amount) {
        var t = Task<int>.Run(() => {
            return CustomerDA.getList(token, page, amount);
        });
        return await t;
    }