Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
163 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...