Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CSHARP

C# Async Function without await

// Sample 2: Async Task, without await for result
// Search for C# Async Function simple for a simple version

// Starts the Task, that wait for G:FILE, then read all content and ends.
Task<string> readTask = Read();
Console.WriteLine("Before file exists...");

// Do Something other, and checks if task completed
bool doMore = true;
while (doMore)
{
    Console.Write("Do more? (Y/n): ");
    string? answer = Console.ReadLine();
    doMore = answer?.ToUpper() != "N";
    if (readTask.IsCompleted)
    {
        string res = readTask.Result;
        Console.Write("The ReadTask was ready, Result: " + res);
        readTask.Dispose();
    }
}


// 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");
    }
}
 
PREVIOUS NEXT
Tagged: #Async #Function #await
ADD COMMENT
Topic
Name
8+2 =