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 collection from an asynchronous method GetNamesAsync:

// Method #1
var names = await GetNamesAsync();
...
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 #2
var names = await GetNamesAsync();
...
public Task<List<string>> GetNamesAsync()
{
    var names = new List<string>();
    names.Add("AAA");
    names.Add("BBB");
    names.Add("CCC");
    return Task.FromResult(names);
}
// Method #3
var names = await GetNamesAsync();
...
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: 2017/05/17 by leszek