C# 异步

WBOY
发布: 2024-09-03 15:31:52
原创
589 人浏览过

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中文网其他相关文章!

相关标签:
来源:php
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板