我正在使用System.Net.Http.HttpClient发出postaysnc请求。在请求进行过程中,我拔下网络电缆,接收HttpRequestException。 一段时间后,再次插入网络电缆并发出postasync请求,得到HttpRequestException-有时我得到响应服务器不可用,有时超时 我是否需要在异常情况下处理httpclient并在发出请求时重新创建?如何使查询在网络还原中成功。
private async Task<string> GetServerResult()
{
try
{
var response = await myHttpClient.PostAsync("https://google.com", httpContent);
response.EnsureSuccessStatusCode();
}
catch (HttpRequestException ex)
{
throw new HttpRequestException(ex.Message, ex.InnerException);
}
}
答案 0 :(得分:0)
根据您的要求,在这种情况下,您必须更改实现某种实现。我提出的解决方案用于WCF客户端的缓存机制,并定期对其进行更新。
非常简单的实现可能是:您有一个非常简单的singleton类,并且定期Timer从您提到的端点中获取数据。它存储了最后缓存的数据,以便您拥有数据的副本;当匹配失败时,您可以为此配置后备机制。例如,您有一个类似
的实现//You single Cache class
public sealed class ClientCache
{
#region Singleton implementation
private static ClientCache _clientCache = new ClientCache();
private ClientCache()
{
}
public static ClientCache Instance => _clientCache;
#endregion
//Timer for syncing the data from Server
private Timer _timer;
//This data is the cached one
public string data = string.Empty;
internal void StartProcess()
{
//Initializing the timer
_timer = new Timer(TimeSpan.FromMinutes(1).TotalMilliseconds); //This timespan is configurable
//Assigning it an elapsed time event
_timer.Elapsed += async (e, args) => await SyncServerData(e, args);
//Starting the timer
_timer.Start();
}
//In this method you will request your server and fetch the latest copy of the data
//In case of failure you can maintain the history of the last disconnected server
private async Task ProcessingMethod(object sender, ElapsedEventArgs e)
{
//First we will stop the timer so that any other hit don't come in the mean while
timer.Stop();
//Call your api here
//Once the hit is completed or failed
//On Success you will be updating the Data object
//data = result from your api call
//Finally start the time again as
timer.Start();
}
}
现在进入第二步,初始化ClientCache类。最好的选择是在Global.asax类中对其进行初始化
protected void Application_Start()
{
//As
ClientCache.Instance.StartProcess();
}
现在,只要您的前端调用该方法,您就无需返回服务器。只需将缓存中的结果发送回:
private Task<string> GetServerResult()
{
return Task.FromResult(ClientCache.Instance.data);
}