I'm having a hard time understanding async
and the corresponding behavior. This is a model of the program I'm trying to write, and a repro of the problem I'm having:
namespace AsyncTesting
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("starting....");
MyClass myClass = new MyClass();
myClass.DoSomeWork();
Console.WriteLine("ending....");
Console.ReadLine();
}
}
class MyClass
{
public bool DoSomeWork()
{
return GetTrue().Result;
}
Task<bool> GetTrue()
{
return new Task<bool>(() => true);
}
}
}
When I make the GetTrue().Result
call, it never returns. My Task<bool> GetTrue()
method is a dummy method for repro purposes, but I'm not quite sure why it never comes back. But it returns if I have this:
namespace AsyncTesting
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("starting....");
MyClass myClass = new MyClass();
myClass.DoSomeWork();
Console.WriteLine("ending....");
Console.ReadLine();
}
}
class MyClass
{
public async void DoSomeWork()
{
await GetTrue();
}
Task<bool> GetTrue()
{
return new Task<bool>(() => true);
}
}
}
The problem is, with my repro I want the initial behavior. I don't want async void
for the calling method. I want to be able to return bool
from my calling "normal" method. How can I achieve this? How can I get the first example to run and actually return the bool
from DoSomeWork()
?
Thank you in advance.
EDIT: Thank you for the answers. I think what the problem is, is that my GetTrue()
method isn't a true repro. In my method, I'm not generating the actual Task<bool>
object. It's really a call to Task.Factory.FromAsync<bool>()
that is creating the Task<bool>
object. And it's that task that I don't know how to "start". Any other ideas? Thanks!