EK_AllDay
EK_AllDay

Reputation: 1115

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()
    { 

    }
}

Upvotes: 5

Views: 10983

Answers (2)

Craig W.
Craig W.

Reputation: 18155

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

Task.Run(() => new Repository().computeLongFunction());
return Request.CreateReponse(HttpStatusCode.Ok);

Upvotes: 5

Donald.Record
Donald.Record

Reputation: 301

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.

Upvotes: 2

Related Questions