0

This is an oversimplified example, but what, if any, benefit is there to using the first example. I see it happening in a lot of places in some projects I inherited. I don't understand the reasoning behind using a thread to execute something if I'm just going to wait for it to finish.

private async void ButtonClicked(object sender, EventArgs args)
{
    await Task.Run(()=>{DoSomething();});
    DoSomethingElse();
}

and this

private void ButtonClicked(object sender, EventArgs args)
{
    DoSomething();
    DoSomethingElse();
}

`

ADyson
  • 57,178
  • 14
  • 51
  • 63
jsureke
  • 79
  • 9
  • 2
    If `DoSomething` needs a lot of time, the first example has the advantage that the GUI does not freeze during the execution of the method. – SomeBody Sep 02 '21 at 11:18
  • 1
    SomeBody is correct (assuming this is a winforms application, not a web application, where this would be happening during postback so the GUI freeze thing wouldn't really apply) – ADyson Sep 02 '21 at 11:20
  • 1
    The only reason you'd do `await Task.Run(()=>{DoSomething();});` in a UI event-handler is when `DoSomething` is a non-`async` method that's also a long-running operation that will block the UI thread (this also assumes that `DoSomethingElse` **is not** a long-running method, so calling it synchronously is fine because it won't block the UI thread for more than 1 frame (i.e. 16ms). – Dai Sep 02 '21 at 11:29
  • 2
    @SomeBody The flip-side is that _the UI is still interactable_ while that operation runs in the background - so if other buttons (which perform conflicting actions) are still enabled then users can break the application. I recommend doing `this.Enabled = false; try { await /*stuff*/ } finally { this.Enabled = false; }` to be safe. – Dai Sep 02 '21 at 11:35
  • @Dai If the GUI freezes and during that period, the user clicks some button, those actions will be executed when the long running operation is finished. Normally, the user will click the buttons several times, because nothing happens, and then the actions are executed several times, which is even more annoying. So even if you don't run your long running operations in a background thread, you will have to disable the GUI elemets. – SomeBody Sep 02 '21 at 11:49
  • 1
    "If the GUI freezes and during that period, the user clicks some button, those actions will be executed when the long running operation is finished." - yes, but those would still run _after_ the long-operation has already finished - I'm saying the issue is that those operations could run _concurrently_, and most stateful software I've seen does not handle concurrent mutations to its in-memory object-graph or external IO, or databases, etc very well because they aren't thread-safe, let alone designed for it. – Dai Sep 02 '21 at 11:50

0 Answers0