什么是同步和异步方法? [英] What's a sync and async method?

查看:82
本文介绍了什么是同步和异步方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是同步方法,什么是异步方法?sync和async方法之间有什么区别?什么时候必须使用同步或异步方法?我问这些问题是因为我不明白:

What's a sync method and what is an async method ? What's the difference between sync and async methods ? When do I have to use sync or async method ? I'm asking those questions because I don't understand :

public async void ReadData(filepath)
{
    CreateDoc("hello");    //<------ Why I can't do that ?
}

public void CreateDoc(string astring)
{
    Debug.WriteLine(astring);
}

为什么我不能那样做?:

And why I can't do that ? :

public async void ReadData(filepath)
{
     var BarreDroite = new string[] { "|" };
     foreach (string tableArret in items.Split(BarreDroite, StringSplitOptions.RemoveEmptyEntries))
     {
         listeArret.Add(tableArret); //<---- Here appear the problem.
     }
{

我问这个问题是因为我在网络上并没有找到明确的解释.

I ask this question because I don't really find clear explanations on the web.

推荐答案

函数和其他操作在线程"上运行.一个线程只是一串操作,但是一次可以有多个线程.在某些方面,最重要的线程是主线程,通常称为UI线程,因为这是控制用户界面的地方.

Functions and other operations operate on "threads." A thread is just a string of operations, but you can have more than one thread at a time. In some ways the most important thread is the main thread, often called the UI thread because this is where the user interface is controlled.

执行冗长的操作(例如从Internet获取数据)时,您不想在主线程上等待该数据,因为您将阻止"该线程响应用户输入(例如,单击取消"按钮))

When performing lengthy operations (such as getting data from the Internet) you do not want to wait for that data on the main thread as you will "block" that thread from responding to user input (for example, clicking the cancel button)

要解决此问题,请将长期运行的任务放在其自己的线程上.C#使此操作变得容易,您只需使用await关键字,该函数将在不阻塞主线程的情况下等待工作完成.

To solve this, you put the long running task on its own thread. C# makes this easy, you just use the await keyword, and the function will await completion of the work without blocking the main thread.

等待"一词是一个关键字",仅用于此目的.要发出一个函数等待状态的信号,必须使用异步标记该函数.如果确实将其标记为异步,则编译器将至少等待一次.

The word await is a "keyword" -- its use is reserved for this purpose. To signal that a function has an await in it, you must mark the function with async. If you do mark it async, the compiler will expect at least one await.

您的示例:

public async void ReadData(filepath)
{
    CreateDoc("hello");    //<------ Why I can't do that ?
}

您已将此方法标记为异步,但没有任何等待状态

You've marked this method async but you don't have any awaits

希望这会有所帮助

杰西

这篇关于什么是同步和异步方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆