简体   繁体   中英

.Net Web API - How to make API Call run synchronously?

I'm building my own Web API project.

In my project, there is an action that needs a long executable time (let's say it takes 2 to 3 minutes to finish) this needs to be run in the background.

How do I return the HTTP 202 when I first call the API, then return another HTTP status code (200 or 500, etc...) when the background task finishes.

Here is my code:

[HttpPost]
//this is the API acttion
public async Task < HttpResponseMessage > PostCoinData() {
    Task.Run(() => {
        //background task to run
        //i want to return another HTTP status code when the task is completed
        return ImportCoinData();
    }).Start();

    //return HTTP 202
    return new HttpResponseMessage(HttpStatusCode.Accepted);
}

private async Task < HttpResponseMessage > ImportCoinData() {
    //get data from db using EF .NET
    List<CoinData> coinDatasInDatabase = await _context.CoinData.ToListAsync();
}

The easiest way is to create a polling service to check the status of the request. There are more sophisticated methods but may be harder to implement. Look at signal R

但是,您可以像下面那样使用“ 射击并忘记”方法

 ThreadPool.QueueUserWorkItem(o => YourMethod());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM