【发布时间】:2021-12-20 20:40:29
【问题描述】:
我有以下代码。代码究竟做了什么?为什么我们需要Stopwatch、XmlSerializer、MemoryStream。使用async/await 是否有更简单的方法?
使用contentResponse.Result; 也会导致死锁情况。
public T GetResponse<T>()
{
var response = default(T);
using (HttpClient httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Add("Authorization", authHeader);
Stopwatch watch = Stopwatch.StartNew();
var contentResponse = httpClient.GetAsync(uri.ToString());
try
{
contentResponse.Wait();
}
catch (Exception exception)
{
}
var wsResponseContent = contentResponse.Result;
wsResponseContent.Content.LoadIntoBufferAsync();
var resultTask = wsResponseContent.Content.ReadAsStringAsync();
resultTask.Wait();
string wsResponseContentText = resultTask.Result;
if (watch.IsRunning)
watch.Stop();
wsResponseContent.EnsureSuccessStatusCode();
if (wsResponseContent.IsSuccessStatusCode)
{
XmlSerializer result = new XmlSerializer(typeof(T));
using (MemoryStream sresultStream = new MemoryStream(Encoding.UTF8.GetBytes(wsResponseContentText)))
{
response = (T)result.Deserialize(sresultStream);
sresultStream.Close();
}
}
}
return response;
}
【问题讨论】:
-
这段代码在很多方面都很糟糕,需要很长时间才能回答。从阅读开始:stackoverflow.com/a/69859015/2141621
-
至于秒表——我看不到它在任何地方都被使用过,所以它几乎和它不存在一样——除了它增加了复杂性。
-
好吧,秒表确实被创建、启动和停止了。所有有用的操作,如果你最终要读取它的值(不像这里,它被忽略了)。摆脱它
-
@JonasH 绝对不可能,“代码到底是做什么的?”代码审查不解释代码。
-
通常秒表有两种使用方式,要么对操作进行基准测试(“这需要多长时间” - 在这种情况下,它会在升级到生产之前被删除)或记录(同样需要多长时间这样做了)。在这种情况下,
watch的范围在using块内。它被创建、启动和停止,但从不读取。它与并行处理没有有关。这里的唯一目的是测量StartNew和Stop之间经过的时间
标签: c# asp.net-mvc-4 asp.net-web-api