Async与Await怎么在C#中使用

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#中使用问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注行业资讯频道了解更多相关知识。