Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CSHARP

C# Async Function with await

// Sample 1: Async Task, with await for result
// Search for C# Async Function without await

// Starts the Task, that wait for G:FILE, then read all content and ends.
Task<string> ReadTask = Read();
Console.WriteLine("Before file exists...");
await ReadTask; // Wait for Result the Task; Create a file "G:FILEx", write Content, Rename to "FILE"

string res = ReadTask.Result;
Console.WriteLine("After:" + res);

// A Async Funktion thats return a Task<String>
static async Task<string> Read()
{
    string rv = "";
    Task task = new Task(ReadTask);

    task.Start();
    // Wait for finish
    await task;

    return rv; // Convertet to Task<string>

    // Without Return-Value, is an Action<>
    void ReadTask()
    {
        while (!System.IO.File.Exists("G:FILE")) System.Threading.Thread.Sleep(100);
        rv = System.IO.File.ReadAllText("G:FILE");
    }
}
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #Async #Function #await
ADD COMMENT
Topic
Name
2+7 =