我有以下WCF合同:
[ServiceContract(Namespace = "http://abc/Services/AdminService")]
public interface IAdminService
{
[OperationContract]
string GetServiceVersion();
// More methods here
}
Run Code Online (Sandbox Code Playgroud)
这GetServiceVersion是一个返回一些字符串的简单方法.它用作ping来检查服务是否可访问.
现在我想异步调用它,认为它比使用.NET线程在后台调用它更有效.
所以,我为此提出了以下接口:
[ServiceContract(Namespace = "http://abc/Services/AdminService")]
public interface IMiniAdminService
{
[OperationContract(Action = "http://abc/Services/AdminService/IAdminService/GetServiceVersion", ReplyAction = "http://abc/Services/AdminService/IAdminService/GetServiceVersionResponse")]
Task<string> GetServiceVersionAsync();
}
Run Code Online (Sandbox Code Playgroud)
这使得可以GetServiceVersion异步调用API:
var tmp = new ChannelFactory<IAdminService>("AdminServiceClientEndpoint");
var channelFactory = new ChannelFactory<IMiniAdminService>(tmp.Endpoint.Binding, tmp.Endpoint.Address);
var miniAdminService = channelFactory.CreateChannel();
return miniAdminService.GetServiceVersionAsync().ContinueWith(t =>
{
if (t.Exception != null)
{
// The Admin Service seems to be unavailable
}
else
{
// The Admin Service is …Run Code Online (Sandbox Code Playgroud) 对此问题予以评论引发的这一个:
如何在async/await没有的情况下将非线性代码反向移植到.NET 4.0 Microsoft.Bcl.Async?
在链接的问题中,我们有一个WebRequest操作,如果它一直失败,我们想要重试有限次数.该Async/await代码看起来是这样的:
async Task<HttpWebResponse> GetResponseWithRetryAsync(string url, int retries)
{
if (retries < 0)
throw new ArgumentOutOfRangeException();
var request = WebRequest.Create(url);
while (true)
{
WebResponse task = null;
try
{
task = request.GetResponseAsync();
return (HttpWebResponse)await task;
}
catch (Exception ex)
{
if (task.IsCanceled)
throw;
if (--retries == 0)
throw; // rethrow last error
// otherwise, log the error and retry
Debug.Print("Retrying after error: " + ex.Message);
}
}
} …Run Code Online (Sandbox Code Playgroud)