0

I am using a third-party library. That library contains an object with an async method that returns Task<SomeStuff>. I am wrapping that object and others into my own class. My wrapper method is also async and has the same return. Calling the wrapper method works fine in my unit tests and a console app. However, it doesn't work in my WPF GUI app. I have tried different methods for invoking in my GUI but nothing works.

In my unit tests, I invoke with GetAwaiter().GetResult(). However, in my GUI this never returns.

I tried using Start() but that results in an error: "Start may not be called on a promise-style task."

What do I need to do to make this work in my GUI?

            // Foo() returns Task<SomeStuff>

            // this works fine in unit test as well as console app, but not in GUI (WPF)
            SomeStuff stuff = myWrapper.Foo().GetAwaiter().GetResult();


            // this results in error: "Start may not be called on a promise-style task."
            Task<SomeStuff> myTask = myWrapper.Foo();
            myTask.Start();
            myTask.Wait();
dkalkwarf
  • 313
  • 2
  • 11
  • Never use `GetResult()` or `Result` or anything like that. Use `await` instead. – Alejandro Jul 01 '21 at 19:38
  • "Never use" doesn't help me much. Perhaps an explanation of why you think it is a bad idea would help. It works fine for me except for the situation I described. In addition, I am not sure await is a solution to my problem. Wouldn't I have to mark my method as async and all the methods that call it. Isn't that what GetAwaiter is for? – dkalkwarf Jul 06 '21 at 13:00

1 Answers1

0

There is a very good discussion of various approaches to my issue here: [https://stackoverflow.com/questions/5095183/how-would-i-run-an-async-taskt-method-synchronously?rq=1][1]

For the moment I resolved my issue as below. I shall re-read the post from the link and perhaps refine my approach.

            Task<SomeStuff> task = Task.Run(() => myWrapper.Foo());

            task.Wait();

            SomeStuff stuff = task.Result;

dkalkwarf
  • 313
  • 2
  • 11