C# 5.0出來已經很久了,之前做項目一直用C#4.0的方法,一直沒時間嚐鮮,最近半年多沒弄C#, 準備撿一撿,給自己練練級。
C# 5.0新出的關鍵字 aynsc 和 await 一般成對使用,直接上代碼
(如果你還是.net Framework4.0的架構不想升級到4.5,沒關係Microsoft.Bcl.Async將幫助你在不升級到4.5的Framework的情況下依然可以用 aynsc 和 await, 下載)
static void Main(string[] args)
{
TestAsync();
Console.WriteLine("主線程消息");
TraceMessage("abc");
while (true)
{
}
}
static Task<double> GetValueAsync(double num1, double num2)
{
return Task.Run(() =>
{
return num1 + num2;
});
}
public static async void TestAsync()
{
Console.WriteLine("123");
Thread.Sleep(1000);
double result =await GetValueAsync(1,3);
Console.WriteLine("Value is : " + result);
}
輸出結果:
123
主線程消息
Value is : 4
結論:async 代表這個函數裏面有異步,但是裏面的異步是從 await 這個函數開始,之前的行還是同步狀態所以先輸出“123”,但是GetValueAsync是異步函數新開了線程,走到這裏主線程認爲TestAsync產生了異步,所以直接接着走,輸出“主線程消息”,但是TestAsync裏面由於await ,所以必須等待GetValueAsync線程結束,就可以輸出“Value is : 4”。
另外C#5.0 Trace .Net 4.5中引入了三個Attribute:CallerMemberName、CallerFilePath和CallerLineNumber
1.區別:
//輸出跟蹤信息
Trace.WriteLine()
將有關跟蹤的信息寫入 Listeners 集合中的跟蹤偵聽器
在調試和release模式都輸出!默認是寫到輸出窗口的,也可以指定寫到指定文件,或系統日誌中!
//輸出調試信息
Debug.WriteLine()
將有關調試的信息寫入Listeners集合中的跟蹤偵聽器 。
只有調試的時候才輸出。
public void TraceMessage(string message,
[CallerMemberName] string memberName = "",
[CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0)
{
Trace.WriteLine("message: " + message);
Trace.WriteLine("member name: " + memberName);
Trace.WriteLine("source file path: " + sourceFilePath);
Trace.WriteLine("source line number: " + sourceLineNumber);
}