编程语言
首页 > 编程语言> > c#-WCF RIA服务超时

c#-WCF RIA服务超时

作者:互联网

我有这样的背景:

[EnableClientAccess()]
public class MyRiaService : LinqToEntitiesDomainService<EntityFrameworkContext>

使用Silverlight客户端,我需要花费1分钟以上的时间来启动繁重的数据库操作.结果,我收到超时异常:

Uncaught Error: Unhandled Error occured in Silverlight Application:
Submit operation failed. for HTTP request to https://localhost/MyProject/ClientBin/myservice.svc/binary has exceeded the allotted timeout. The time allotted to this operation may have been a portion of a longer timeout.

Stack Trace:
  at System.Windows.Ria.OperationBase.Complete(Exception error)
  at System.Windows.Ria.SubmitOperation.Complete(Exception error)
  at System.Windows.Ria.DomainContext.CompleteSubmitChanges(IAsyncResult asyncResult)
  at System.Windows.Ria.DomainContext.<>c_DisplayClassd.b_5(Object )

我很乐意在那里更改发送超时,但是我不知道如何更改.
我已经试过了:

((WebDomainClient<LibraryDomainContext.ILibraryDomainServiceContract>)this.DomainClient).ChannelFactory.Endpoint.Binding.SendTimeout = new TimeSpan(0, 5, 0);

但是我没有属性DomainClient.

解决方法:

可以在域服务端点上的客户端上设置连接的超时.但是如何掌握呢?通过为域上下文创建扩展方法:

public static class DomainServiceExtensions
{
    /// <summary>
    /// This method changes the send timeout for the specified 
    /// <see cref="DomainContext"/> to the specifified <see cref="TimeSpan"/>.
    /// </summary>
    /// <param name="domainContext">
    /// The <see cref="DomainContext"/> that is to be modified.
    /// </param>
    /// <param name="newTimeout">The new timeout value.</param>
    public static void ChangeTimeout(this DomainContext domainContext, 
                                          TimeSpan newTimeout)
    {
        // Try to get the channel factory property from the domain client 
        // of the domain context. In case that this property does not exist
        // we throw an invalid operation exception.
        var channelFactoryProperty = domainContext.DomainClient.GetType().GetProperty("ChannelFactory");
        if(channelFactoryProperty == null)
        {
            throw new InvalidOperationException("The 'ChannelFactory' property on the DomainClient does not exist.");
        }

        // Now get the channel factory from the domain client and set the
        // new timeout to the binding of the service endpoint.
        var factory = (ChannelFactory)channelFactoryProperty.GetValue(domainContext.DomainClient, null);
        factory.Endpoint.Binding.SendTimeout = newTimeout;
    }
}

有趣的问题是何时将调用此方法.一旦使用了端点,就无法再更改超时.因此,在创建域上下文后立即设置超时:

DomainContext类本身是密封的,但幸运的是,该类也被标记为局部的-方法OnCreated()可以很容易地以这种方式扩展.

public partial class MyDomainContext
{
    partial void OnCreated()
    {
        this.ChangeTimeout(new TimeSpan(0,10,0));
    }
}

专业提示:实现部分类时,该类所有部分的名称空间必须相同.此处列出的代码属于客户端项目(例如,具有名称空间RIAServicesExample),但是上面显示的部分类仍需要驻留在服务器端名称空间中(例如RIAServicesExample.Web).

标签:wcf-ria-services,silverlight-3-0,c,silverlight
来源: https://codeday.me/bug/20191123/2066460.html