C # Pause loop and continue after button click

I have a method that is called after the initialization component, the method signature is like:

public async void method_name ()
{
    // code ...
}

      

Inside this method, I have a loop with 4 different operators if

. I need a loop to pause in each if statement and wait for the user to click the button. Since clicking this button will add information and stuff. Once the button is clicked, I want the loop to continue and of course pause in the next if statements.

I thought about doing it like await Task.Delay(30000);

, but if the user has finished entering information before this timer expires, he / she will just wait. and that it is not effective.

+3


source to share


1 answer


You can do this with TaskCompletionSource

. Create it and wait for its properties Task

and when the button is clicked use it to do this task. This allows you to asynchronously await user input without blocking the thread or using Task.Delay

.



TaskCompletionSource<bool> _tcs;

async Task Foo()
{
    // stuff
    _tcs = new TaskCompletionSource<bool>();
    await _tcs.Task
    // other stuff
}

void ButtonClicked(object sender, EventArgs e)
{
    _tcs.SetResult(false);
}

      

+7


source







All Articles