kong88
kong88

Reputation: 117

Async programming in C#

I'm trying to get my head around asynchronous programming in C#. I've created a basic WPF program. This includes a new class CleaningService that has an async Start() method. The WPF program has a button that calls the Start() method on click.

Within this Start() method, I want to call an async Method1() method and then an async Method2() method.

When I click on the button, Method2() doesn't get called. Why would this be the case?

Code:

class CleaningService : ICleaningService
{
    private bool _continue;

    public async void Start()
    {
        this._continue = true;

        if (!await this.Method1())
        {
            this._continue = false;
        }

        if (!await this.Method2())
        {
            this._continue = false;
        }
    }

    public void Cancel()
    {
        this._continue = false;
    }

    public async Task<bool> Method1()
    {
        // do something
        Console.WriteLine("Processing Method1..");
        return await new Task<bool>(() => true);
    }

    public async Task<bool> Method2()
    {
        if (this._continue)
        {
            // do something
            Console.WriteLine("Processing Method2..");
            return await new Task<bool>(() => true);
        }
        else
        {
            return await new Task<bool>(() => false);
        }
    }
}

Upvotes: 1

Views: 469

Answers (1)

Andr&#233;s Robinet
Andr&#233;s Robinet

Reputation: 1537

You never started the task in Method1 (you just created a Task, but it was never started)

Upvotes: 3

Related Questions