-->

What's a sync and async method?

2020-01-19 09:01发布

问题:

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.

回答1:

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.

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)

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.

Your examples:

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

Hope this helps

jesse



回答2:

  1. Synchronization means two or more operations are running in a same context (thread) so that one may block another.
  2. Synchronization means two or more operations happen sequentially.
  3. Asynchronous means two or more operations are running in different contexts (thread) so that they can run concurrently and do not block each other.
  4. Asynchronous means two or more operations happen asynchronously.

You can read more on the below thread: http://www.codeproject.com/Articles/127660/What-are-actually-synchronous-asynchronous-operati