开发者

Threads inside Wcf

I have WCF service Service with some method LongTimeMethod. To avoid request timeout I do next:

    public void LongTimeMethod(...)
    {
        Thread t = new Thread(delegate() {
            LocalL开发者_开发百科ongTimeMethod(...);
        });
        t.IsBackground = true;
        t.Start();
    }

    private void LocalLongTimeMethod(...)
    {
      SomeOperations();
    }

After that SomeOperations runs 10 times faster(!?). The result of SomeOperations is right. So what is the reason and is it normal?

One more question: is Service instance alive while my thread hasn't finished?


So what is the reason and is it normal?

The method is unlikely to be executing 10 times faster. Since your WCF operation is a void - you aren't returning anything. Rather, the introduction is the thread is allowing the WCF operation to complete and it will keep processing your work on a different thread.

So you call your WCF operation, it fires off a thread, and completes. It isn't going to wait for the thread to finish. If the client calls the operation synchronously, it will appear to have completed to the client even though the background thread is still there doing all the work.

This is often called "Fire-and-forget".

A better option for this that is built into WCF is to create a One Way Contract.

is Service instance alive while my thread hasn't finished?

Most likely it is.


In addition to what vcsjones said, if you're going to fire and forget, use ThreadPool.QueueUserWorkitem on the server side. Do not create a thread. Server processes such as ASP.net and WCF have a pool of threads which make it more efficient (creating a thread allocates 1MB of thread storage etc...) but more importantly, it ensures that a surge of requests won't take down your server - instead it blocks waiting getting a thread from the pool.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜