Question Details

No question body available.

Tags

c# wpf async

Answers (1)

November 21, 2025 Score: 2 Rep: 6,407 Quality: Low Completeness: 60%

Am I reinventing the wheel here? I can't really find anything online talking about this type of problem but I can't be the first person to struggle with the issue?

I don't think this kind of use case is very common. Usually the window itself would be responsible for any setup and teardown if such is needed. So I'm not all that surprised that there is a lack of resources.

Is there an easier way to approach this problem?

Either of your options looks fine to me. I would not expect to use this pattern all that often, so I would not worry to much about making it super neat. Just make sure to provide comments to explain what problem the code aims to solve.

If you want to provide a meaningful result you could use generics with a constraint. And there is no need to use async in the helper method. I think something like this should work:

public static Task ShowAsync(this TWindow w, Func getResult) where TWindow : Window
{
    TaskCompletionSource tcs = new();
    w.Closing += (o, e) =>
    {
       if(w.DialogResult == true){
          tcs.SetResult(getResult(w));
       }
       else{
          tcs.SetCanceled(); // Make sure to catch OperationCancelledException
       }       
    };

w.Show(); return tcs.Task; }

This feels like it might to balloon into a real nightmare to maintain. Has anyone gone down this path before?

Using asynchronous programming will add some complexity, but I would not call it a maintenance nightmare. While this kind of thing is not the main use case of asynchronous programming, it can still be a useful pattern.

Not quite the same, but I have used TaskCompletionSource as a way to build state machines before, where the user needs to perform a series of specific actions in sequence. This added a fair bit of complexity in all the helper classes, but the code for the state machine is fairly easy to read since it is almost like regular synchronous code. I prefer this over the alternative of writing out the state machine as a huge switch statement myself.

But this is a discussion you should have in your team. Things like pattern and coding style can be very opinion based, and it is sometimes more important to have a cohesive style that you all agree with than to use the best possible pattern for a given situation.