【发布时间】:2015-04-18 05:34:24
【问题描述】:
我们遇到了来自 WPF 应用程序的后台调用问题。看起来,在较旧的计算机上(我们最常在具有 2GB RAM 左右的 Windows 7 计算机上看到它)我们的 Web 服务调用 阻塞 UI 直到它完成。特别是对于一个呼叫,这是一个巨大的问题,因为它可能需要五分钟才能完成。较新的计算机似乎可以很好地处理它。
我们不关心通话花费的时间;我们只关心它不会阻塞 UI。我没有看到我们做错了什么。
是我们做错了什么,还是 Windows 7 在 2GB RAM 上的问题?有没有办法在这样的机器上解决它?
我们是否必须达到编写自定义TaskScheduler 的水平以确保不使用 UI 线程?我当然希望不会。
非常感谢任何输入。提前致谢。请参阅下面的代码示例。
DownloadBusinessEntityAsync 是我们的应用程序调用的方法:
#region DownloadBusinessEntity
public async Task<BusinessEntity> DownloadBusinessEntityAsync(string businessEnityId)
{
BusinessEntity ret = new BusinessEntity();
var client = new DownloadContext();
try
{
Func<AsyncCallback, object, IAsyncResult> begin = (callback, state) => client.BeginDownloadBusinessEntity(businessEnityId, callback, state);
Func<IAsyncResult, BusinessEntity> end = client.EndDownloadBusinessEntity;
// ***THIS TAKES FIVE MINUTES TO FINISH***
ret = await Task<BusinessEntity>.Factory.FromAsync(begin, end, null);
if (client.State != CommunicationState.Faulted)
client.Close();
else
client.Abort();
}
catch (Exception ex)
{
client.Abort();
}
return ret;
}
#endregion
DownloadContext 是 WCF 客户端:
public partial class DownloadContext : ClientBase<IDownloadService>, IDownloadService, IDownloadContext, IDisposable
{
public BusinessEntity DownloadBusinessEntity(string agencyId, IEnumerable<int> activeHashCodes)
{
return base.Channel.DownloadBusinessEntity(agencyId, activeHashCodes);
}
public IAsyncResult BeginDownloadBusinessEntity(string agencyId, IEnumerable<int> activeHashCodes, AsyncCallback callback, object asyncState)
{
return base.Channel.BeginDownloadBusinessEntity(agencyId, activeHashCodes, callback, asyncState);
}
public BusinessEntity EndDownloadBusinessEntity(IAsyncResult result)
{
return base.Channel.EndDownloadBusinessEntity(result);
}
}
IDownloadService 是 WCF 客户端实现的合同。
[ServiceContract(Namespace = "http://namespace.com/services/v1")]
public partial interface IDownloadService
{
[OperationContract(ProtectionLevel=ProtectionLevel.Sign, Action="http://namespace.com/services/v1/IDownloadService/DownloadBusinessEntity", ReplyAction="http://namespace.com/services/v1/IDownloadService/DownloadBusinessEntityResponse")]
BusinessEntity DownloadBusinessEntity(string agencyId, IEnumerable<int> activeHashCodes);
[OperationContract(AsyncPattern=true, ProtectionLevel=ProtectionLevel.Sign, Action="http://namespace.com/services/v1/IDownloadService/DownloadBusinessEntity", ReplyAction="http://namespace.com/services/v1/IDownloadService/DownloadBusinessEntityResponse")]
IAsyncResult BeginDownloadBusinessEntity(string agencyId, IEnumerable<int> activeHashCodes, AsyncCallback callback, object asyncState);
BusinessEntity EndDownloadBusinessEntity(IAsyncResult result);
}
【问题讨论】:
标签: wcf asynchronous