C# 非同步

WBOY
WBOY原創
2024-09-03 15:31:52617瀏覽

C# 中非同步執行的特殊方法稱為非同步方法,可以使用修飾符async 使方法非同步,並且可以使用C# 中的非同步方法執行非同步任務,並且可以使用await 表達式暫停方法執行C# 中,如果具有修飾符async 的方法中不存在此等待表達式,則即使該方法是非同步方法且非同步方法的傳回類型為Task、Task,也會同步且非同步執行對應的方法, Void(對於事件處理程序)和System.Threading.Tasks.ValueTask.

C# 非同步方法的語法:

public async Task<int> Method_name()
{
// Block of code
}
  • async 是使用的修飾符。
  • Methodname 是給方法的名稱。

C# 中非同步方法的工作

  • 每當程式中的邏輯需要使用可等待任務時,我們都會使用非同步方法,使用它可以執行需要很長時間才能完成的操作,例如從網路下載某些內容、讀取大檔案或執行計算這確實很複雜,但不會幹擾或阻止應用程式的正常執行。這可以透過在我們的程式中使用修飾符 async 和 wait 來實現。
  • 非同步方法與與其關聯的任務分開調用,該任務執行與程序流程無關的任務,並使其等待,在此期間它可以完成任務並返回相應的值它的定義可以在以下語句中使用,或者它可以仍在執行任務,同時控制權轉到非同步方法的呼叫者並恢復程式的執行而不中斷任​​務的執行,一旦任務完成,非同步方法的其餘部分被執行,並根據其定義返回相應的值。

C# 非同步範例

下面給出的是提到的例子:

範例#1

C# 程式示範程式中的非同步方法讀取檔案內容並決定檔案中的字元數。

代碼:

using System;
using System.IO;
using System.Threading.Tasks;
//a class called check is defined
class Check
{
//main method is called
public static void Main()
{
//a file is created
String pat = @"D:\Ext.txt";
//an instance of the string writer class is created, and the path of the file is passed as a parameter to append text to the file
using (StreamWritersw = File.AppendText(pat))
{
//data to be appended to the file is included
sw.WriteLine("Welcome to StreamWriter class in C#");
//the instance of the streamwriter class is closed after writing data to the File
sw.Close();
}
//ReadFileusingAsync method is called by creating a task and the control moves to ReadFileusingAsync method
Task<int>taskname = ReadFileusingAsync();
//When the control reaches await modifier in ReadFileusingAsync method, the control returns here as the task is still going on and the following statements are executed
Console.WriteLine("Task is being performed by the asynchronous method and we are asked to wait until the completion of the task using await method");
string givemeinput = Console.ReadLine();
Console.WriteLine("The flow of the program is resumed once the task is completed by the asynchronous method and the value is returned " + givemeinput);
//We are waiting to receive the value from the task of asynchronous method in case the value is not returned yet.
taskname.Wait();
//We have used Result method to obtain the value returned from the asynchronous method after the completion of task assigned to it
var z = taskname.Result;
Console.WriteLine("The number of characters in the file are: " + z);
Console.WriteLine("The program has completed its normal execution and the asynchronous method has read the file to count the number of characters in the file");
Console.ReadLine();
}
static async Task<int>ReadFileusingAsync()
{
string fileread = @"D:\Ext.txt";
//The following statements are executed which can take a longer time
Console.WriteLine("We have opened the file to read the contents of the file");
int counter = 0;
using (StreamReader read = new StreamReader(fileread))
{
//await modifier is used to ask the caller function to wait till the reading of the file is complete
string vart = await read.ReadToEndAsync();
counter += vart.Length;
//This is the unnecessary code that is time consuming we have included for the sake of explanation
for (int r = 0; r < 20000; r++)
{
int z = vart.GetHashCode();
if (z == 0)
{
counter--;
}
}
}
Console.WriteLine("We are done reading the file");
return counter;
}
}

輸出:

C# 非同步

說明:

  • 在上面的程式中,定義了一個名為 check 的類,然後呼叫 main 方法,在該方法中我們建立一個檔案並將內容寫入檔案。
  • 然後建立一個任務,該任務呼叫非同步方法 ReadFileusingAsync,並且控制權移至該方法,在該方法中執行讀取檔案內容的任務。
  • 然後在讀取檔案內容的同時使用length函數取得字元的長度,並將其傳回給呼叫方法。
  • 呼叫方法會等待,直到控制權返回它,然後恢復正常的程式流程以顯示結果。

範例#2

用於示範程式中非同步方法的 C# 程式。

代碼:

using System;
using System.Threading.Tasks;
//a class called check is defined
class Check
{
static void Main()
{
while (true)
{
//the asynchronous method is called.
keeptrying();
string res = Console.ReadLine();
Console.WriteLine("The input given by the user while the computation is going on by the asynchronous method is: " + res);
}
}
static async void keeptrying()
{
//the caller function is asked to await
int t = await Task.Run(() =>compute());
Console.WriteLine("The total digits count in the string is: " + t);
}
static intcompute()
{
int counter = 0;
for (int a = 0; a < 10; a++)
{
for (int b = 0; b < 1000; b++)
{
string value = b.ToString();
counter += value.Length;
}
}
return counter;
}
}

輸出:

C# 非同步

說明:

  • 在上面的程式中,定義了一個名為 check 的類別。
  • 然後呼叫main 方法,在該方法中呼叫非同步方法,並且控制移動到非同步方法,在該方法中計算字串中的數字總數,該方法要求呼叫者方法等待,而main 方法繼續顯示使用者提供的輸入。

以上是C# 非同步的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
上一篇:C# 等待異步下一篇:C# 等待異步