Is there a way to wait synchronously for an async method that runs on the same thread?
The desired effect is
- to have the Worker() run asynchronously on the UI thread
- and at the same time wait for it to finish before the Close() method returns
The example below enters in a deadlock, and if I make Form1_FormClosing() async I don't satisfy the second condition.
public partial class Form1 : Form
{
TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
CancellationTokenSource cts = new CancellationTokenSource();
public Form1()
{
InitializeComponent();
Show();
Worker(cts.Token); // async worker started on UI thread
}
async void Worker(CancellationToken ct)
{
while (!ct.IsCancellationRequested)
await TaskEx.Delay(1000);
tcs.SetResult(true); // signal completition
}
private void button1_Click(object sender, EventArgs e)
{
Close();
MessageBox.Show("This is supposed to be second");
}
private async void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
cts.Cancel(); // request cancel
tcs.Task.Wait(); // deadlock
await tcs.Task; // button1_Click() gets control back instead of Worker()
MessageBox.Show("This is supposed to be first");
}
}