jtkSource
jtkSource

Reputation: 685

Async method not calling

Calling the awaitMethod() doesn't print the the second call of the console.printline in GetFilmCount() nor does the last print statement in awaitMethod() gets called. The only output is the Console.printLine() in the first call to GetFilmCount().

Am I doing something wrong here. Cant figure out why its behaving like this ??

public async void awaitMethod()
{
    int count1 = await GetFilmCount(1);
    int count2 = await GetFilmCount(2);

    Console.WriteLine("Number of films {0}, {1} ", count1,count2 );
}

public async Task<int> GetFilmCount(int count)
{
    Console.WriteLine("Count {0} ", count);

    using (MySqlConnection connection = new MySqlConnection(connectionString))
    { 
        connection.Open();

        MySqlCommand cmd = new MySqlCommand("select sleep(5) ; select count(*) from sakila.film", connection);

        return await cmd.ExecuteScalarAsync().ContinueWith(t => {
            return Convert.ToInt32(t.Result);
        });
    }
}

Upvotes: 1

Views: 894

Answers (1)

i3arnon
i3arnon

Reputation: 116538

You shouldn't be using async void unless it's a UI event handler (which doesn't seem to be the case).

What probably happens here is that you're not waiting for awaitMethod to complete (you can't because it's a void method) and so your console application ends before the rest of your code has a chance to execute.

Use async Task instead and await (or call Wait() if it's in Main) the returned Task:

public async Task awaitMethod()
{
    int count1 = await GetFilmCount(1);
    int count2 = await GetFilmCount(2);

    Console.WriteLine("Number of films {0}, {1} ", count1,count2 );
}

Upvotes: 4

Related Questions