How and when to use "asynchronous" and "wait"

This translation from: How to use and the when 'the async' and 'the await'

My Understanding at The One of the From main Things that asyncandawait do the Easy IS to the make code and the Read to the Write - But IS equal is a using Them to spawning background to the perform Threads Long DURATION Logic? According to my understanding, asyncandawait one of the main things to do is to It makes the code easier to write and read - but with whether they are equal to generate a background thread to execute time logic?

I'm currently trying out the most basic example. I am currently trying to basic example. I've added some comments inline. I added some comments in a row. Can you clarify it for me? Can you clarify for me, please?

// I don't understand why this method must be marked as `async`.
private async void button1_Click(object sender, EventArgs e)
{
    Task<int> access = DoSomethingAsync();
    // task independent stuff here

    // this line is reached after the 5 seconds sleep from 
    // DoSomethingAsync() method. Shouldn't it be reached immediately? 
    int a = 1; 

    // from my understanding the waiting should be done here.
    int x = await access; 
}

async Task<int> DoSomethingAsync()
{
    // is this executed on a background thread?
    System.Threading.Thread.Sleep(5000);
    return 1;
}

#1st Floor

Reference: https://stackoom.com/question/yeTt/ how and when to use - asynchronous - and - wait


#2nd Floor

I think you've picked a bad example with System.Threading.Thread.Sleep I think you System.Threading.Thread.Sleephave chosen the wrong example

AN of Point asyncTask IT IS the Execute in background to the let the without locking the Thread at The main, SUCH AS A doing DownloadFileAsync asyncthe task asyncis to make it run in the background without locking the main thread, such as executionDownloadFileAsync

System.Threading.Thread.Sleepis not something that is "being done ", it just sleeps, and therefore your next line is reached after 5 seconds ... System.Threading.Thread.Sleepinstead of "completing" the stuff, it's just sleeping, so to reach the next line in 5 seconds .. .

Article This article was the Read, the I of Think IT IS A Great explanation of the this asyncand awaitConcept: http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx reading this article, I think it is asyncand awaitwell explained concepts : HTTP : //msdn.microsoft.com/zh-cn/library/vstudio/hh191443.aspx


#3rd floor

Answers to at The OTHER Further, have have A look AT await (C # Reference) to learn more about other answers and see await (C # Reference)

and more specifically at the example included, it explains your situation a bit more specifically, in the examples contained herein, which describes you slightly

The following Windows Forms example illustrates the use of await in an async method, WaitAsynchronouslyAsync. The following example illustrates the use Windows Forms await the asynchronous method WaitAsynchronouslyAsync. Contrast the behavior of that method with the behavior of WaitSynchronously. Comparison with WaitSynchronously The behavior of the method. Without an await operator applied to a task , WaitSynchronously runs synchronously despite the use of the async modifier in its definition and a call to Thread.Sleep in its body. Not be applied to await operator task, although in its definition of async modifiers and calls Thread.Sleep in its body, but still WaitSynchronously synchronous operation.

private async void button1_Click(object sender, EventArgs e)
{
    // Call the method that runs asynchronously.
    string result = await WaitAsynchronouslyAsync();

    // Call the method that runs synchronously.
    //string result = await WaitSynchronously ();

    // Display the result.
    textBox1.Text += result;
}

// The following method runs asynchronously. The UI thread is not
// blocked during the delay. You can move or resize the Form1 window 
// while Task.Delay is running.
public async Task<string> WaitAsynchronouslyAsync()
{
    await Task.Delay(10000);
    return "Finished";
}

// The following method runs synchronously, despite the use of async.
// You cannot move or resize the Form1 window while Thread.Sleep
// is running because the UI thread is blocked.
public async Task<string> WaitSynchronously()
{
    // Add a using directive for System.Threading.
    Thread.Sleep(10000);
    return "Finished";
}

#4th floor

BE honest the I Still of Think the To at The Best One explanation at The IS ON Promises and the About Future at The Wikipedia: http://en.wikipedia.org/wiki/Futures_and_promises To be honest, I still think the best explanation is that on Wikipedia about the future and promised to explain: HTTP : //en.wikipedia.org/wiki/Futures_and_promises

The basic idea is that you have a separate pool of threads that execute tasks asynchronously. The basic idea is that you have a separate thread pool, thread pool asynchronous execution of these tasks. When using it. Use. The object does however make the promise that it will execute the operation at some time and give you the result when you request it. However, this object is indeed guaranteed to perform the operation at a time, and provide the results to you when you request . This means that it will block when you request the result and has not finished, but execute in the thread pool otherwise. This means that it will result in your request and obstruction has not been completed, otherwise it will be performed in the thread pool.

From there you can optimize things: some operations can be implemented async and you can optimize things like file IO and network communication by batching together subsequent requests and / or reordering them. You can optimize from there: You can achieve some asynchronous operation, also together and / or to optimize the function of reordering the file IO and a network communication or the like can be obtained by a combination of the subsequent request. I'm not sure if this is already in the task framework of Microsoft - but if it is not that would be one of the first things I would add. I'm not sure if it already exists in the framework of the mandate of Microsoft - but if No, it would be the first thing I want to add.

You can actually implement the future pattern sort -of with yields in C # 4.0. You can actually use yields in C # 4.0 model of the future realization of the sort. How you want to know IF IT Works exactly, the I CAN the Recommend that the this Link A Decent does the Job: http://code.google.com/p/fracture/source/browse/trunk/Squared/TaskLib/ . If you want to know how it works, I can recommend this link, it did a good job: HTTP : //code.google.com/p/fracture/source/browse/trunk/Squared/TaskLib/ . However, if you start toying with it yourself, you will notice that you really need language support if you want to do all the cool things -. Which is exactly what Microsoft did , however, if you start playing with it yourself, you will notice If you want to do all the cool things that you really need language support - this is what Microsoft did.


#5th Floor

From my understanding one of the main things that async and await do is to make code easy to write and read. As I understand it, and wait for asynchronous one main thing to do is to make the code easier to write and read.

To the make're They Asynchronous code the Easy and the Read to the Write, yes. They are designed to make asynchronous code is easy to write and read.

Is it the same thing as spawning background threads to long duration logic perform? Execution time and logic generates a background thread is the same?

Not at all. Not at all.

The I do not Understand Why // the this Method, the MUST BE Marked AS 'the async'. // I do not understand why this method must be marked as "asynchronous."

At The asynckeyword the Enables at The awaitkeyword. asyncKeyword Enable awaitkeyword. The using the any Method SO awaitMUST BE Marked async. Thus, any use of awaitthe method must be marked async.

// This line is reached after the 5 seconds sleep from DoSomethingAsync () method. // After sleeping from DoSomethingAsync () method 5 seconds, reaches this line. Should not it be reached immediately? Should not reach now?

NO, Because asyncMethods are not the Thread Another RUN ON by default. No, because the default asyncmethod does not run on other threads.

Is is the this the Executed ON A // background the Thread? // This is executed on a background thread do?

No. no.


May the Find My by You async/ awaitIntro helpful. You might find me async/ awaitpresentation helpful. At The Official the MSDN docs are unusually Also Good (as particularly at The TAP Section), and at The asyncTeam PUT OUT AN Excellent the FAQ . The MSDN official documents also exceptional (especially the TAP section), and the asyncteam released great the FAQ .


#6th floor

The using the when asyncand awaitThe State Machine Compiler. Generates A The background in. Use async, and await, the compiler generates a state machine in the background.

Here's an example on which I hope I can explain some of the high-level details that are going on: This is an example, I wish I could explain some of the high-level details of what is happening:

public async Task MyMethodAsync()
{
    Task<int> longRunningTask = LongRunningOperationAsync();
    // independent work which doesn't need the result of LongRunningOperationAsync can be done here

    //and now we call await on the task 
    int result = await longRunningTask;
    //use the result 
    Console.WriteLine(result);
}

public async Task<int> LongRunningOperationAsync() // assume we return an int from this long running operation 
{
    await Task.Delay(1000); // 1 second delay
    return 1;
}

OK, so what happens here: OK, so what happened here:

  1. Task<int> longRunningTask = LongRunningOperationAsync(); starts executing LongRunningOperation startedLongRunningOperation

  2. Work IS DONE ON the let work of the Independent apos the ASSUME the Main the Thread The (the Thread ID = 1) the then await longRunningTaskIS Reached. Assume that the primary thread (thread ID = 1) work independently, and then await longRunningTaskreach.

    Now, at The IF longRunningTaskhas not Finished and IT IS Still running, MyMethodAsync()by Will Calling Method, return to the ITS, the Thread does not THUS at The main GET blocked. Now, if longRunningTasknot yet complete and is still running, MyMethodAsync()will return to its caller method, and therefore the main thread will not be blocked. The when at The longRunningTaskIS DONE the then A the Thread from at The ThreadPool (CAN BE the any the Thread) by Will return to MyMethodAsync()in the ITS Previous context and the Continue Execution (in the this Case Printing at The the Result to at The Console). When longRunningTaskthe time is completed, the thread from the ThreadPool (can be any thread) will return to its previous context MyMethodAsync()and continue (in this case, the results printed to the console).

Would that BE SECOND Case A The longRunningTaskhas already Finished Result The ITS and IS Available Execution. The second case longRunningTaskhas completed its execution and the result is available. At The reaching the when await longRunningTaskWE already have have the Result SO at The Executing the Continue at The code by Will. ON the Thread at The Very Same, when arriving await longRunningTaskwe have the results, so the code will continue to execute on the same thread. (Case Printing the Result in the this to Console). (In this case, the result will be printed to the console). The IS Not the this Course Of Case for The above Example, there apos WHERE A Task.Delay(1000)Involved. Of course, for the example above, is not the case, which involves Task.Delay(1000).

Original articles published 0 · won praise 73 · views 550 000 +

Guess you like

Origin blog.csdn.net/w36680130/article/details/105313735