【发布时间】:2010-05-11 13:11:33
【问题描述】:
我是 WCF 的新手。我之前写过 ajax 来使用 Web 服务,但是在这个项目中我试图将 ajax 用于 WCF。
在我使用 ajax 构建项目和 wcf 后,我成功收到了返回。但是,10 分钟或更长时间后我没有得到返回,ajax 调用错误函数,提琴手什么也没返回。
如果我在不修改任何源的情况下重新构建项目,我会再次成功收到返回。
有没有人经历过或者知道为什么会这样?
谢谢。
【问题讨论】:
我是 WCF 的新手。我之前写过 ajax 来使用 Web 服务,但是在这个项目中我试图将 ajax 用于 WCF。
在我使用 ajax 构建项目和 wcf 后,我成功收到了返回。但是,10 分钟或更长时间后我没有得到返回,ajax 调用错误函数,提琴手什么也没返回。
如果我在不修改任何源的情况下重新构建项目,我会再次成功收到返回。
有没有人经历过或者知道为什么会这样?
谢谢。
【问题讨论】:
您很可能没有关闭连接。您应该将所有调用包装在 Try/Catch/Finally 块中。
在 C# 中:
ServiceClient 服务 = GetService();
try
{
SomeRequest request = new SomeRequest();
SomeResponse response = service.GetSome(request);
return response.Result;
}
catch (Exception ex)
{
// do some error handling
}
finally
{
try
{
if (service.State != CommunicationState.Faulted)
{
service.Close();
}
}
catch (Exception ex)
{
service.Abort();
}
}
或VB
Dim service As ServiceClient = GetService()
Try
Dim request As New SomeRequest()
Dim response As SomeResponse = service.GetSome(request)
Return response.Result
Catch ex As Exception
' do some error handling
Finally
Try
If service.State <> CommunicationState.Faulted Then
service.Close()
End If
Catch ex As Exception
service.Abort()
End Try
End Try
【讨论】:
这是调用 WCF 服务的最佳实践:
public static void CallService<T>(Action<T> action) where T
: class, ICommunicationObject, new()
{
var client = new T();
try
{
action(client);
client.Close();
}
finally
{
if (client.State == CommunicationState.Opened)
{
try
{
client.Close();
}
catch (CommunicationObjectFaultedException)
{
client.Abort();
}
catch (TimeoutException)
{
client.Abort();
}
}
if (client.State != CommunicationState.Closed)
{
client.Abort();
}
}
}
每个 WCF 调用都应该为您的服务类创建一个新实例。这段代码允许您强制执行,只需像这样调用服务:
CallService<MyService>( t => t.CallMyService());
【讨论】: