비동기적으로 실행되는 C#의 특수 메서드를 비동기 메서드라고 하며 async 수식자를 사용하여 메서드를 비동기화할 수 있으며, C#에서는 비동기 메서드를 사용하여 비동기 작업을 수행할 수 있고, 메서드 실행은 대기 표현식을 사용하여 일시 중단할 수 있습니다. C# 및 async 수정자가 있는 메서드에 이 Wait 표현식이 없으면 해당 메서드는 메서드가 비동기 메서드이고 비동기 메서드의 반환 유형이 Task, Task
C# 비동기 방식의 구문:
public async Task<int> Method_name() { // Block of code }
다음은 언급된 예입니다.
파일 내용을 읽고 파일의 문자 수를 확인하는 프로그램의 비동기식 방법을 보여주는 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# 프로그램
코드:
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# 비동기의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!