Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebAPI Threading

So I have a function that has a long wait time during its computation. I have a endpoint that needs to call this function, however it does not care about the completion of the function.

public HttpResponseMessage endPoint
{
    Repository repo= new Repository();
    // I want repo.computeLongFunction(); to be called, however this endpoint
    // can return a http status code "ok" even if the long function hasn't completed.

    repo.computeLongFunction();

    return Request.CreateReponse(HttpStatusCode.Ok);
}

// If I make the function async would that work?
public class Repository
{ 
    public void compluteLongFunction()
    { 

    }
}
like image 876
EK_AllDay Avatar asked Apr 13 '15 20:04

EK_AllDay


People also ask

Is Webapi multi threaded?

The Web API already has a pool of threads to use, so no need to worry about multithreading. Why does a thread pool resolve in a programmer not having to worry about threading?

Is Web API single threaded?

Answering the question, JavaScript is single-threaded in the same context, but browser Web APIs are not.

What is API multithreading?

The multithreaded API permits applications to create multiple sessions with the IBM Spectrum Protect server within the same process. The API can be entered again. Any calls can run in parallel from within different threads.

What is threading in .NET framework?

Threads are tasks that can run concurrently to other threads and can share data. When your program starts, it creates a thread for the entry point of your program, usually a Main function.


2 Answers

Use the Task Parallel Library (TPL) to spin off a new thread.

Task.Run(() => new Repository().computeLongFunction());
return Request.CreateReponse(HttpStatusCode.Ok);
like image 175
Craig W. Avatar answered Sep 29 '22 12:09

Craig W.


It doesn't look like computeLongFunction() returns anything, so try this:

Thread longThread = new Thread(() => new Repository().computeLongFunction());
longThread.Start();

return Request.CreateResponse(HttpStatusCode.Ok);

Declare the thread so that you will still be able to control its life-cycle.

like image 23
Donald.Record Avatar answered Sep 29 '22 13:09

Donald.Record