溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Async與Await怎么在C#中使用

發布時間:2021-01-06 17:05:34 來源:億速云 閱讀:211 作者:Leah 欄目:編程語言

Async與Await怎么在C#中使用?針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

Async 和 await是代碼標記,它標記代碼位置為任務完成后控件應該恢復的位置。

下面讓我們舉幾個例子來更好進行理解吧

C#中Async 和 await關鍵字的示例

我們將采用控制臺應用程序進行演示。

第一個例子

在這個例子中,我們將采取兩個不相互依賴的方法。

class Program
{ 
  static void Main(string[] args)
  { 
Method1();
Method2();
Console.ReadKey();
  } 
 
  public static async Task Method1()
  { 
await Task.Run(() =>
    { 
      for (int i = 0; i < 100; i++)
      { 
Console.WriteLine(" Method 1"); 
      } 
    }); 
  } 
 
 
  public static void Method2()
  { 
    for (int i = 0; i < 25; i++)
    { 
Console.WriteLine(" Method 2"); 
    } 
  } 
}

在上面給出的代碼中,Method 1和Method 2不相互依賴,我們是從主方法調用的。

在這里,我們可以清楚地看到,方法1和方法2并不是在等待對方完成。

輸出

Async與Await怎么在C#中使用

現在來看第二個例子,假設我們有Method 3,它依賴于Method 1

第二個例子

在本例中,Method 1將總長度作為整數值返回,我們在Method 3中以長度的形式傳遞一個參數,它來自Method 1。

在這里,在傳遞Method 3中的參數之前,我們必須使用AWAIT關鍵字,為此,我們必須使用調用方法中的async 關鍵字。

在控制臺應用程序的Main方法中,因為不能使用async關鍵字而不能使用await 關鍵字,因為它會給出下面給出的錯誤。(但是如果你使用的是C#7.1及以上的方法是不會有問題的,因為C#7.1及以上的語法支持Mian方法前加async)

Async與Await怎么在C#中使用 

我們將創建一個新的方法,作為CallMethod,在這個方法中,我們將調用我們的所有方法,分別為Method 1、Method 2和Method 3。

class Program
{ 
  static void Main(string[] args)
  { 
callMethod();
Console.ReadKey();
  } 
 
  public static async void callMethod()
  { 
Task<int> task = Method1();
Method2();
    int count = await task;
Method3(count);
  } 
 
  public static async Task<int> Method1()
  { 
    int count = 0;
await Task.Run(() =>
    { 
      for (int i = 0; i < 100; i++)
      { 
Console.WriteLine(" Method 1"); 
count += 1;
      } 
    }); 
    return count;
  } 
 
  public static void Method2()
  { 
    for (int i = 0; i < 25; i++)
    { 
Console.WriteLine(" Method 2"); 
    } 
  } 
 
  public static void Method3(int count)
  { 
Console.WriteLine("Total count is " + count);
  } 
}

在上面給出的代碼中,Method 3需要一個參數,即Method 1的返回類型。在這里,await關鍵字對于等待Method 1任務的完成起著至關重要的作用。

輸出

Async與Await怎么在C#中使用

第三個例子

.NET Framework4.5中有一些支持API,Windows運行時包含支持異步編程的方法。

在Async 和 await關鍵字的幫助下,我們可以在實時項目中使用所有這些,以便更快地執行任務。

包含異步方法的API有HttpClient, SyndicationClient, StorageFile, StreamWriter, StreamReader, XmlReader, MediaCapture, BitmapEncoder, BitmapDecoder 等。

在本例中,我們將異步讀取大型文本文件中的所有字符,并獲取所有字符的總長度。

class Program
{ 
  static void Main()
  { 
Task task = new Task(CallMethod);
task.Start();
task.Wait();
Console.ReadLine();
  } 
 
  static async void CallMethod()
  { 
    string filePath = "E:\\sampleFile.txt"; 
Task<int> task = ReadFile(filePath);
 
Console.WriteLine(" Other Work 1"); 
Console.WriteLine(" Other Work 2"); 
Console.WriteLine(" Other Work 3"); 
 
    int length = await task;
Console.WriteLine(" Total length: " + length);
 
Console.WriteLine(" After work 1"); 
Console.WriteLine(" After work 2"); 
  } 
 
  static async Task<int> ReadFile(string file)
  { 
    int length = 0;
 
Console.WriteLine(" File reading is stating"); 
    using (StreamReader reader = new StreamReader(file))
    { 
      // Reads all characters from the current position to the end of the stream asynchronously  
      // and returns them as one string.  
      string s = await reader.ReadToEndAsync();
 
length = s.Length;
    } 
Console.WriteLine(" File reading is completed"); 
    return length;
  } 
}

在上面給出的代碼中,我們調用ReadFile方法來讀取文本文件的內容,并獲取文本文件中總字符的長度。

在sampleText.txt中,文件包含了太多的字符,因此讀取所有字符需要很長時間。

在這里,我們使用異步編程從文件中讀取所有內容,所以它不會等待從這個方法獲得一個返回值并執行其他代碼行,但是它必須等待下面給出的代碼行,因為我們使用的是等待關鍵字,我們將對下面給出的代碼行使用返回值。

int length = await task;
Console.WriteLine(" Total length: " + length);

隨后,將按順序執行其他代碼行。

Console.WriteLine(" After work 1"); 
Console.WriteLine(" After work 2");

輸出

Async與Await怎么在C#中使用

關于Async與Await怎么在C#中使用問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業資訊頻道了解更多相關知識。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女