D.Costa D.Costa - 4 months ago 11
C# Question

What's a sync and async method?

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.

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

Comments