如何在异步ASP.NET Web服务调用上定义客户端超时?

时间:2011-06-28 06:50:24

标签: c# web-services soap asynchronous timeout

今天我已经搜索了一些特定的案例来调用具有以下要求的(外部)ASP.NET Web服务:

  • 调用必须以异步方式完成
  • 必须实施超时,因为Web服务可能需要很长时间才能执行

在互联网和StackOverflow上出现了很多关于此主题的问题,但要么使用日期,要么建议使用WebRequest.TimeOut属性,该属性仅适用于同步调用。

另一种方法是使用System.Threading.Timer。在开始呼叫之前启动计时器,并在达到TimerCallback时取消它。

但是,我认为对这种情况应该有一种更常见的方法。不幸的是到目前为止找不到它。任何人都有想法在异步Web服务调用上设置客户端超时?

提前致谢。

5 个答案:

答案 0 :(得分:8)

实际上,您不能总是使用WebRequest.TimeOut进行异步操作;至少不适用于抽象WebRequest类的所有实现者。例如,msdn上记录了此属性is ignored when calling HttpWebRequest.BeginGetResponse启动异步操作。明确声明TimeOut属性被忽略,如果需要,用户有责任实现超时行为。

HttpWebRequest.BeginGetResponse documentation on msdn附带的示例代码中,ManualResestEvent allDoneWaitOrTimerCallback的组合使用如下:

IAsyncResult result = (IAsyncResult) myHttpWebRequest.BeginGetResponse(
  new AsyncCallback(RespCallback), myRequestState);

// TimeoutCallback aborts the request if the timer fires.
ThreadPool.RegisterWaitForSingleObject (result.AsyncWaitHandle, 
                                        new WaitOrTimerCallback(TimeoutCallback),
                                        myHttpWebRequest, 
                                        DefaultTimeout, 
                                        true);

// The response came in the allowed time. The work processing will happen in the 
// callback function RespCallback.
allDone.WaitOne();

请参阅complete example on msdn

最重要的是你必须亲自实现这一点。

答案 1 :(得分:8)

请检查你的app.config它将有一些servicemodel的设置,它有各种可配置的值。

当我添加新的服务参考时,我可以在app.config中看到以下内容,

<system.serviceModel>
    <bindings>
        <basicHttpBinding>
            <binding name="HeaderedServiceSoap" 
                     closeTimeout="00:01:00" 
                     openTimeout="00:01:00"
                     receiveTimeout="00:10:00" 
                     sendTimeout="00:01:00" 
                     allowCookies="false"
                     bypassProxyOnLocal="false" 
                     hostNameComparisonMode="StrongWildcard"
                     maxBufferSize="65536" 
                     maxBufferPoolSize="524288" 
                     maxReceivedMessageSize="65536"
                     messageEncoding="Text" 
                     textEncoding="utf-8" 
                     transferMode="Buffered"
                     useDefaultWebProxy="true">
                <readerQuotas maxDepth="32" 
                              maxStringContentLength="8192" 
                              maxArrayLength="16384"
                              maxBytesPerRead="4096" 
                              maxNameTableCharCount="16384" />
                <security mode="None">
                    <transport clientCredentialType="None" 
                               proxyCredentialType="None"
                               realm="" />
                    <message clientCredentialType="UserName" 
                             algorithmSuite="Default" />
                </security>
            </binding>
        </basicHttpBinding>
    </bindings>
    <client>
        <endpoint 
          address="http://localhost/MyService.asmx"
          binding="basicHttpBinding" 
          bindingConfiguration="HeaderedServiceSoap"
          contract="WSTest.HeaderedServiceSoap" 
          name="HeaderedServiceSoap" />
    </client>
</system.serviceModel>

尝试再次删除和添加引用,确保您的应用程序的目标框架是4.0,并且您正在添加服务引用(不是Web引用)。

答案 2 :(得分:2)

我开展了一个小项目,展示了如何做到这一点;它并不像我想象的那么简单,但是,那是什么呢?

这是整个项目的一个Web服务,也是WPF中的一个客户端,它有一个按钮,用于调用带有和不带超时的http://www.mediafire.com/file/3xj4o16hgzm139a/ASPWebserviceAsyncTimeouts.zip。我会在下面放一些相关的片段。我使用了代码中描述的DispatcherTimer类来执行超时;看起来这个对象显然是WPF友好的,并且(应该)解除大部分(如果不是全部)可能遇到的同步问题。

注意:它可能以某种方式使用WCF风格的“服务引用”来完成,但是,我无法找到方法并且遇到很多死胡同。我终于得到了一个较老的“Web Reference”(你可以通过转到“Add Service Reference ...”,选择“Advanced”按钮,然后选择“Add Web Reference”。

我参加帮助班的原因是为了证明在你有很多电话的情况下可以做些什么。如果我们没有这样的话,跟踪一切都会很快变得混乱。此外,它可能有一个更通用的版本,其中几乎所有的处理都可以在代码中完成,但由于泛型的方式,花费我大部分时间的WCF代码不适合这种处理。用于服务参考代码。我只是很快看了一下网络服务代码,它看起来更有可能完成,但遗憾的是我没有足够的时间来处理这部分事情。让我知道你是否希望我再看看,我会看到我能做些什么。

现在开始演出! ;)

执行回调的助手:AsyncCallHelper.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

// contains base classes for webservice calls
using System.ServiceModel; 

// contains the DispatcherTimer class for callback timers
using System.Windows.Threading; 

namespace ASPSandcastleWPFClient
{
    /// <summary>
    /// DispatcherTimer usage info thanks to:
    /// 
    /// Wildermuth, Shawn, "Build More Responsive Apps With The Dispatcher", MSDN Magazine, October 2007
    /// Original URL: http://msdn.microsoft.com/en-us/magazine/cc163328.aspx
    /// Archived at http://www.webcitation.org/605qBiUEC on July 11, 2011.
    /// 
    /// this class is not set up to handle multiple outstanding calls on the same async call;
    /// if you wish to do that, there would need to be some sort of handling for multiple
    /// outstanding calls designed into the helper.
    /// </summary>
    public class AsyncCallHelper
    {
        #region Static Defaults
        private static TimeSpan myDefaultTimeout;
        /// <summary>
        /// default timeout for all instances of the helper; should different timeouts
        /// be required, a member should be created that can override this setting.
        /// 
        /// if this is set to null or a value less than zero, the timout will be set 
        /// to TimeSpan.Zero, and the helper will not provide timeout services to the 
        /// async call.
        /// </summary>
        public static TimeSpan DefaultTimeout
        {
            get
            {
                return myDefaultTimeout;
            }
            set
            {
                if ((value == null) || (value < TimeSpan.Zero))
                    myDefaultTimeout = TimeSpan.Zero;
                else
                    myDefaultTimeout = value;
            }
        }
        #endregion

        /// <summary>
        /// creates an instance of the helper to assist in timing out on an async call
        /// </summary>
        /// <param name="AsyncCall">the call which is represented by this instance. may not be null.</param>
        /// <param name="FailureAction">an action to take, if any, upon the failure of the call. may be null.</param>
        public AsyncCallHelper(Action AsyncCall, Action FailureAction)
        {
            myAsyncCall = AsyncCall;
            myFailureAction = FailureAction;

            myTimer = new DispatcherTimer();
            myTimer.Interval = DefaultTimeout;
            myTimer.Tick += new EventHandler(myTimer_Tick);
        }

        /// <summary>
        /// Make the call
        /// </summary>
        public void BeginAsyncCall()
        {
            myAsyncCall();

            if (DefaultTimeout > TimeSpan.Zero)
            {
                myTimer.Interval = DefaultTimeout;
                myTimer.Start();
            }
        }

        /// <summary>
        /// The client should call this upon receiving a response from the
        /// async call.  According to the reference given above, it seems that 
        /// the WPF will only be calling this on the same thread as the UI, 
        /// so there should be no real synchronization issues here.  
        /// 
        /// In a true multi-threading situation, it would be necessary to use
        /// some sort of thread synchronization, such as lock() statements
        /// or a Mutex in order to prevent the condition where the call completes
        /// successfully, but the timer fires prior to calling "CallComplete"
        /// thus firing the FailureAction after the success of the call.
        /// </summary>
        public void CallComplete()
        {
            if ((DefaultTimeout != TimeSpan.Zero) && myTimer.IsEnabled)
                myTimer.Stop();
        }

        private void myTimer_Tick(object sender, EventArgs e)
        {
            CallComplete();

            if (myFailureAction != null)
                myFailureAction();
        }

        /// <summary>
        /// WPF-friendly timer for use in aborting "Async" Webservice calls
        /// </summary>
        private DispatcherTimer myTimer;

        /// <summary>
        /// The call to be made
        /// </summary>
        private Action myAsyncCall;

        /// <summary>
        /// What action the helper should take upon a failure
        /// </summary>
        private Action myFailureAction;
    }

}

带有relvant代码的MainWindow.xaml.cs文件:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using ASPSandcastleWPFClient.ASPSandcastleWebserviceClient;

namespace ASPSandcastleWPFClient
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private ASPSandcastleWebservice myClient = null;
        private AsyncCallHelper myHelloWorldHelper = null;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void InitializeClient()
        {
            myClient = new ASPSandcastleWebservice();
            myHelloWorldHelper = 
                new AsyncCallHelper
                    (
                        myClient.HelloWorldAsync,
                        HelloWorldTimeout
                    );
        }

        private void Window_Initialized(object sender, EventArgs e)
        {
            InitializeClient();
        }

        /// <summary>
        /// this is called prior to making a call so that we do not end up with multiple
        /// outstanding async calls
        /// </summary>
        private void DisableButtons()
        {
            btnStartAsyncCall.IsEnabled = false;
            btnStartAsyncCallWithTimeout.IsEnabled = false;
        }

        /// <summary>
        /// this is called after a result is received or the call is cancelled due to timeout
        /// so that we know it's safe to make another call.
        /// </summary>
        private void EnableButtons()
        {
            btnStartAsyncCall.IsEnabled = true;
            btnStartAsyncCallWithTimeout.IsEnabled = true;
        }

        private void btnStartAsyncCall_Click(object sender, RoutedEventArgs e)
        {
            DisableButtons();

            // disable the timeout handling
            AsyncCallHelper.DefaultTimeout = TimeSpan.Zero;

            myClient.HelloWorldCompleted += new HelloWorldCompletedEventHandler(myClient_HelloWorldCompleted);

            myHelloWorldHelper.BeginAsyncCall();
            lblResponse.Content = "waiting...";
        }

        private void btnStartAsyncCallWithTimeout_Click(object sender, RoutedEventArgs e)
        {
            DisableButtons();

            // enable the timeout handling
            AsyncCallHelper.DefaultTimeout = TimeSpan.FromSeconds(10);
            lblResponse.Content = "waiting for 10 seconds...";
            myHelloWorldHelper.BeginAsyncCall();
        }

        /// <summary>
        /// see note RE: possible multi-thread issues when not using WPF in AsyncCallHelper.cs
        /// </summary>
        private void HelloWorldTimeout()
        {
            myClient.CancelAsync(null);
            lblResponse.Content = "call timed out...";
            EnableButtons();
        }

        void myClient_HelloWorldCompleted(object sender, HelloWorldCompletedEventArgs e)
        {
            myHelloWorldHelper.CallComplete();

            if (!e.Cancelled)
                lblResponse.Content = e.Result;

            EnableButtons();
        }
    }
}

答案 3 :(得分:1)

我不知道它是否是惯用的,但我还通过DispatchTimer发出异步请求时使用Silverlight中的计时器(WebClient.DownloadStringAsync(...))。

答案 4 :(得分:0)

Web服务返回什么? XML,JSON还是其他?你是否像网站一样使用它?如果是这样,为什么不尝试使用jquery ajax调用,然后可以将其加载为异步,并且可以使用.ajax()指定超时。