-3

So I have some code that I need to execute when an form activates its Shown event, and I need to await that code. I am doing this:

form.Shown += async (sender, args) => await BufferOpen(CurrentPath, CurrentEncoding, 1024 * 1024 * 5, statusProgressForm.progressBar1);
                statusProgressForm.Show();

But the code still continues without awaiting the BufferOpen method. How can I do this with an anonymous function?

EDIT: Ok, so I think I screwed up the original post. Sorry about that. What I'm really trying to do is show a form and THEN on the shown event perform intensive code, as before when I just did this:

form.Show();
DoIntensiveTasks();

The GUI on the form would not properly load and the labels and such wouldn't display properly. I need to wait until the form is completely shown then do stuff.

Visual User
  • 69
  • 1
  • 6
  • The code you have there hooks up an event handler and then shows a `statusProgressForm`. When the event handler is called, it asynchronously calls BufferOpen and returns immediately. So which code are you referring to when you say "but the code still continues"? Why wouldn't it? Which code do you expect to "wait" before being executed? – andrew Jan 01 '20 at 02:53
  • Events are not really friendly with async as you've noticed but your question has already been answered here: https://stackoverflow.com/questions/12451609/how-to-await-raising-an-eventhandler-event – Thadeu Fernandes Jan 01 '20 at 03:11
  • @ThadeuFernandes `async` was literally design to be in event handlers as it's *primary* use case. Saying it's not designed to be used with events is just not true. – Servy Jan 01 '20 at 03:30
  • Sorry, I mean in this specific context, where one delegate/method bound to the event needs to be awaited. Events don't discriminate sync and async delegates, they are just invoked and async delegates don't reply back to the caller's context. – Thadeu Fernandes Jan 01 '20 at 03:37

1 Answers1

2

The problem is that because you used an expression lambda it's only performing the one expression as a part of that anonymous method, and thus the Show call isn't a part of that anonymous method. All it takes is to use brackets to make it a statement lambda:

form.Shown += async (sender, args) =>
{
    await BufferOpen(CurrentPath, CurrentEncoding, 1024 * 1024 * 5, statusProgressForm.progressBar1);
    statusProgressForm.Show();
};
Servy
  • 202,030
  • 26
  • 332
  • 449