[英]Real advantages of Async-Await?
剛才我已經發布了這個問題涉及到在客戶端或服務應用異步等待。 在繼續討論該問題之前,請務必先閱讀該問題,因為它與該問題緊密相關。
根據答案,我已經測試了C#4.0(TPL)和C#5.0(異步-等待)的代碼。 我正在使用服務提供的方法的異步和同步版本來調用服務,並比較每種情況下使用的線程數。 以下是我用來測試所用資源的代碼:
主要方法
List<Task<string>> tasksList = new List<Task<string>>();
List<int> asyncThreads = new List<int>();
List<int> tplThreads = new List<int>();
Stopwatch watch = new Stopwatch();
watch.Start();
// Call the Async version of the method
for (int i = 0; i < 500; i++)
{
tasksList.Add(GetNameFromServiceAsync("Input" + i.ToString(), asyncThreads));
}
Task.WaitAll(tasksList.ToArray());
watch.Stop();
foreach (var item in asyncThreads.Distinct())
{
Console.WriteLine(item);
}
Console.WriteLine("(C# 5.0)Asynchrony Total Threads = " + asyncThreads.Distinct().Count());
Console.WriteLine(watch.ElapsedMilliseconds.ToString());
watch.Restart();
tasksList.Clear();
// Call the normal method
for (int i = 0; i < 500; i++)
{
tasksList.Add(GetNameFromService("Input" + i.ToString(), tplThreads));
}
Task.WaitAll(tasksList.ToArray());
watch.Stop();
foreach (var item in tplThreads.Distinct())
{
Console.WriteLine(item);
}
Console.WriteLine("(C# 4.0)TPL Total Threads" + tplThreads.Distinct().Count());
Console.WriteLine(watch.ElapsedMilliseconds.ToString());
異步和同步呼叫到服務
static async Task<string> GetNameFromServiceAsync(string name, List<int> threads)
{
Console.WriteLine(" Start Current Thread : " + System.Threading.Thread.CurrentThread.ManagedThreadId);
var task = await client.GetNameAsync(name);
threads.Add(System.Threading.Thread.CurrentThread.ManagedThreadId);
// Console.WriteLine("End GetNameFromServiceAsync Current Thread : " + System.Threading.Thread.CurrentThread.ManagedThreadId);
return task;
}
static Task<string> GetNameFromService(string name, List<int> threads)
{
var task = Task<string>.Factory.StartNew(() =>
{
threads.Add(System.Threading.Thread.CurrentThread.ManagedThreadId);
// Console.WriteLine("GetNameFromService Current Thread : " + System.Threading.Thread.CurrentThread.ManagedThreadId);
return client.GetName(name);
});
return task;
}
現在,我一直在研究答案,並找出以下結果:
我希望對自己的發現有一些反饋,以便對其他社區成員也有用。 這是我先前問題的答案嗎?
編輯
問:我的觀察得出的結論是,如果我們使用Async-Await代替TPL的Task.Factory.startNew,那么它將消耗更少的線程。 這有多正確? 如果否,那么進行這種比較的正確方向是什么?
問:當我正在學習異步時-等待,我想通過某種比較和可靠的代碼來證明它的價值。
客戶端async
(與同步代碼相比)通常以較小的內存成本來提高響應速度。
服務器端async
(與同步代碼相比)通常通過減少內存/線程使用量來提高可伸縮性。 這些優勢也適用於客戶端async
(與多線程代碼相比)。
兩者都是極端概括,當然在某些情況下它們是錯誤的。
更新:
我的觀察得出的結論是,如果我們使用Async-Await ...,那么它將消耗較少的線程。
async
/ await
啟用可維護的異步代碼。 就其本身而言,它們與創建線程無關。 但是,它們通常與Task.Run
(或Task.Factory.StartNew
)一起使用以創建后台任務。
當我正在學習異步時-等待,我想通過某種比較和可靠的代碼來證明它的價值。
async
和await
是編譯器轉換。 它們使編寫異步程序變得更容易-僅此而已。
如果將它們與同步代碼進行比較,則通常會看到改進的響應能力和/或可伸縮性。 如果將它們與現有的異步代碼進行比較,那么它們的效率通常會稍差一些,但在代碼可維護性方面要比彌補它們的效率更高。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.