【发布时间】:2021-11-08 20:59:44
【问题描述】:
我想知道您的反馈以优化代码。这会导致死锁或性能问题吗?这是调用 Web API 方法并使用 .Net 4.7
一些帖子建议在使用 GetAsync 时使用 async 和 await 以避免死锁。是否应该使用 HttpRequestException 处理、TaskCanceledException 和 CancelPendingRequests?
public ItemDTO GetItem(int itemId)
{
var result = new ItemDTO();
try
{
var client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });
var response = client.GetAsync(String.Format(apiUrl + "store/GetItemDetails/{0}", itemId)).Result;
if (response.IsSuccessStatusCode)
result = response.Content.ReadAsAsync<ItemDTO>().Result;
else
throw new Exception(response.StatusCode + " - " + response.ReasonPhrase);
}
catch (Exception ex)
{
Store.ManageException.HandleException(ex);
throw new GetItemsException(ex.Message);
}
return result;
}
更新: 有时 IIS 服务器会挂起。这是 DebugDiag2 分析 - CrashHangAnalysis 报告。这会导致死锁吗?
Thread ID Total CPU Time Entry Point for Thread
2 00:00:00.031 ntdll!RtlReleaseSRWLockExclusive+2200
0 00:00:00.030 w3wp+2e50
1 00:00:00.000 nativerd!DllGetClassObject+24680
3 00:00:00.000 ntdll!RtlReleaseSRWLockExclusive+2200
4 00:00:00.000 w3tp!THREAD_POOL::CreateThreadPool+350
4 Threads (40% of all threads) have this same call stack.
Note: Grouping of identical threads can be disabled in the 'Preferences' tab of the Analysis Options
Thread 2 - System ID 4704
Entry point ntdll!RtlReleaseSRWLockExclusive+2200
Create time 9/20/2021 1:00:34 PM
Time spent in user mode 0 Days 00:00:00.000
Time spent in kernel mode 0 Days 00:00:00.031
This thread is not fully resolved and may or may not be a problem. Further analysis of these threads may be required.
Thread 3 - System ID 2576
Entry point ntdll!RtlReleaseSRWLockExclusive+2200
Create time 9/20/2021 1:00:34 PM
Time spent in user mode 0 Days 00:00:00.000
Time spent in kernel mode 0 Days 00:00:00.000
This thread is not fully resolved and may or may not be a problem. Further analysis of these threads may be required.
Thread 8 - System ID 2112
Entry point ntdll!RtlReleaseSRWLockExclusive+2200
Create time 9/20/2021 1:00:34 PM
Time spent in user mode 0 Days 00:00:00.000
Time spent in kernel mode 0 Days 00:00:00.000
This thread is not fully resolved and may or may not be a problem. Further analysis of these threads may be required.
Thread 9 - System ID 5832
Entry point ntdll!RtlReleaseSRWLockExclusive+2200
Create time 9/20/2021 1:01:04 PM
Time spent in user mode 0 Days 00:00:00.000
Time spent in kernel mode 0 Days 00:00:00.000
This thread is not fully resolved and may or may not be a problem. Further analysis of these threads may be required.
Instruction Address Source
[0x7ffadb029444] ntdll!NtWaitForWorkViaWorkerFactory+14
[0x7ffadaf9eb4e] ntdll!RtlReleaseSRWLockExclusive+296e
[0x7ffada7184d4] kernel32!BaseThreadInitThunk+14
[0x7ffadafd1781] ntdll!RtlUserThreadStart+21
【问题讨论】:
标签: asp.net-mvc asp.net-web-api optimization async-await deadlock