Question

I have created a web service with HttpListener For some requests it needs long running jobs which might take about 10 minutes. So I do following and return from server:

var task = Task.Factory.StartNew(() => ImportDocuments(), TaskCreationOptions.LongRunning);
CreateResponse(context.Response, "started");

Is this guaranteed to return from server and launch a new thread to complete task or I have to use Process.Start? I didn't use Process.Start as I have to than implement a separate application than windows application.

Was it helpful?

Solution

You definitely don't have to use Process.Start.

I've yet to find any guarantee that using TaskCreationOptions.LongRunning always fires tasks on a new Thread independent of the ThreadPool, but the implication is such. The best I can find is that it:

provides a hint to the scheduler that an additional thread might be required for the task so that it does not block the forward progress of other threads or work items on the local queue.

But goes on to state that:

By using this option you avoid the ThreadPool completely, including the global and local queues.

Hint or guarantee? I'm fairly sure it's guaranteed, but it's only an opinion and IMO the docs don't categorically back this up.

A small amount of work with a decompiler will tell you the truth.

If you're still not happy, then:

new Thread(() => {
    //my long running code
}).Start();

will absolutely guarantee that long running work doesn't starve your ThreadPool. Just make sure you don't kill your CPU with a billion threads.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top