1

I'm looking to create an extension method with the following signature:

public static IObservable<DialogResult> ShowDialog(this Form form);

I don't know how to get this to work. This is what I have so far:

Task<DialogResult> task = Task.Factory.StartNew(() =>
{
    return form.ShowDialog();
});
return task.ToObservable();

Edit: Cool, thanks guys. I really need to read up on this stuff some more!

potato
  • 41
  • 6
  • 3
    Why do you want this? And what do you think will happen if you do UI work in a non-UI thread? – Peter Bons Dec 15 '16 at 08:28
  • I don't know. I'm really new to this and am trying to write all my code asynchronously using Reactive Extensions. – potato Dec 15 '16 at 19:12
  • 1
    Please don't. try only running code async when it makes senses. You better read when you should apply it and then apply it in a good manner. This is bound to fail. Harse words but well intended advice. Use it when doing I/O operations for example, or when heavy cpu work needs to be done on a separate thread. Writing async code should not be a goal but a means to solve specific issues. – Peter Bons Dec 15 '16 at 19:41

1 Answers1

0

I imagine this would work, though I don't understand the point.

public static class Extensions
{
    public static IObservable<DialogResult> ShowDialogObservable(this Form form)
    {
        return Observable.Create<DialogResult>(o =>
        {
            o.OnNext(form.ShowDialog());
            return Disposable.Empty;
        });
    }
}
Shlomo
  • 14,102
  • 3
  • 28
  • 43
  • Thanks, I'm trying to return the DialogResult asynchronously, though I don't know if it's possible with ShowDialog – potato Dec 15 '16 at 19:10
  • @Peter had solid advice here. There's no way to truly turn a closed synchronous method into an asynchronous one. `ShowDialog` is meant to be a blocking, synchronous method. If you wanted the non-blocking form, you would use `Show`. Doing this still blocks threads, resources, etc.. – Shlomo Dec 15 '16 at 20:10