1

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);
        }
    }
}
1
  • You should never use the task constructor. Ever. Commented Dec 19, 2016 at 2:22

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

Ah thanks. I guess I should just do something like Thread.Sleep(1); instead.
You can do use Task.Run(...)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.