I have a method that is called after the initialization component, the method signature is like:
public async void method_name ()
{
// code ...
}
Inside that method, I have a loop running with 4 different if
statements. I need the loop to pause at each if statements and wait for the user to press a button. Since pressing that button will add info and stuff. Once the button is pressed, I want the loop to continue and of course pause at the next if statements.
I thought about doing it like await Task.Delay(30000);
but if the user is done entering the info before that timer is over, he/she will just be waiting. and That's not efficient.
You can do that with TaskCompletionSource
. Create it and await its Task
property and when a button is clicked use it to complete that task. That allows to asynchronously wait for the user input without blocking a 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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.