简体   繁体   中英

WCF server-side timeout

有没有办法告诉 WCF 服务在一段时间后响应请求(无论是否中止它的处理),即使它还没有完成,比如服务器端超时策略?

I suppose you could do this by starting a new Thread as soon as the WCF operation starts. The real work then happens on the new thread and the original WCF request thread waits using a Thread.Join() with a specific timeout. If the timeout occurs the worker thread can be canceled using a Thread.Abort().

Something like this:

public string GetData(int value)
{
    string result = "";
    var worker = new Thread((state) =>
    {
        // Simulate l0ng running
        Thread.Sleep(TimeSpan.FromSeconds(value));
        result = string.Format("You entered: {0}", value);
    });

    worker.Start();

    if (!worker.Join(TimeSpan.FromSeconds(5)))
    {
        worker.Abort();
        throw new FaultException("Work took to long.");
    }

    return result;
}

I have solved the same problem and created a blog post:

http://kanchengcao.blogspot.com/2012/06/adding-timeout-and-congestion.html

In short:

  1. WCF server timeout config do not work
  2. You could implement a timeout as others said
  3. Such a timeout does not guarantee a timely response to the client, since the request could be queued for long before entering your code with timeout.

So I implemented method to drop requests if the server is overloaded and is expected to cause more timeouts.

I don't know why you want to do this - you should probably edit your question to say what you're trying to accomplish.

If I had to do this, then I would have the web service pass the request off to a separate Windows Service, possibly by using WCF over MSMQ. I would have a timeout on that request. If the request didn't finish in time, I'd simply return a Timeout fault. The actual request would not be impacted.

Implement your service using the asynchronous model and have some code monitoring your outstanding requests to see if they've taken too long.

Then, if a timeout occurs before the request can be answered in the real way, then call their callback. The WCF stack provides this when it calls your

BeginFoo( fooParam1, fooParam2, AsyncCallback callback, object state)

Then throw or return your fault/timeout exception or response in the correponding EndFoo() method.

Make sure to not call their callback again if the real answer comes along eventually.

It'll take some getting used to asynchronous wcf programming, but no, apparently there is no server side setting.

Also, you should try to use a client that supports timeout or cancellable requests because you might not be able to rely on the server to time out the request for you. There might not be connectivity or the server machine might have another problem.

Cheers, Chris

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