User Tools

Site Tools


notes:csharp:tasks

Tasks in C#

Example: Wait for an asynchronous method to complete:

Task.Run(async () => { await Initialize(); }).Wait();
...
private async Task Initialize()
{
    // asynchronous code goes here
}

Example: Return a stub task from an async method:

public  Task LoadAsync()
{
    return Task.Delay(0);
}

Example: Return a collection from an asynchronous method GetNamesAsync:

var names = await GetNamesAsync();
// Method #1
public async Task<List<string>> GetNamesAsync()
{
    await Task.Yield();
    return new List<string>()
    {
        "AAA",
        "BBB",
        "CCC"
    };
}
// Method #2
public Task<List<string>> GetNamesAsync()
{
    return Task.Run(() =>
    {
        var names = new List<string>();
        names.Add("AAA");
        names.Add("BBB");
        names.Add("CCC");
        return names;
    });
}  
// Method #3
public Task<List<string>> GetNamesAsync()
{
    var names = new List<string>();
    names.Add("AAA");
    names.Add("BBB");
    names.Add("CCC");
    return Task.FromResult(names);
}
// Method #4
public async Task<List<string>> GetNamesAsync()
{
    var task = Task.Run(() => GetNames());
    List<string> names = await task;
    return names;
}
 
private List<string> GetNames()
{
    var names = new List<string>();
    names.Add("AAA");
    names.Add("BBB");
    names.Add("CCC");
    return names;
}

Example: Execute a long running “fire-and-forget” method:

await DoWork();
...
private async Task DoWork()
{
    await Task.Run(() =>
    {
        // A long running task goes here.
        for (int i = 0; i < 1000000000; ++i)
        {
            //...
        }
    });
}

Example: Wait until all tasks are completed:

var tasks = new Task[]
{
    Task.Run(() =>
    {
        var data1 = GetData1();
        // ... do something with data1
    }),
    Task.Run(() =>
    {
        var data2 = GetData2();
        // ... do something with data2
    }),
    Task.Run(() =>
    {
        var data3 = GetData3();
        // ... do something with data3
    })
};
await Task.Run(() => Task.WaitAll(tasks));
...
string GetData1() { return "A"; }
string GetData2() { return "B"; }
string GetData3() { return "C"; }  
notes/csharp/tasks.txt · Last modified: 2018/02/22 by leszek