Getting task results from synchronous execution

I find it difficult to understand the asynccorresponding behavior. This is the model of the program I'm trying to write, and the reproduction of the problem that I am 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 a call GetTrue().Result, he never returns. My method Task<bool> GetTrue()is a dummy method for playback purposes, but I'm not quite sure why it never returns. But it comes back 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 that with my playback I want the initial behavior. I do not want async voidfor the calling method. I want to return boolfrom my usual method. How can i achieve this? How can I get the first example to run and actually return boolfrom DoSomeWork()?

Thanks in advance.

EDIT: . , , GetTrue() . Task<bool>. Task.Factory.FromAsync<bool>(), Task<bool>. , , "". ? !

+4
2

, , :

Task<bool> GetTrue()
{
    return Task.FromResult(true);
}

:

Task<bool> GetTrue()
{
    return new Task<bool>(() => true);
}

. Task.Run Task.RunSynchronously. new Task(). Stephen Toub "Task.Factory.StartNew" (...). " " Task.Run vs Task.Factory.StartNew ".

, , :

Task<bool> GetTrue()
{
    return Task.Run(() => true);
}

-, ?".

:

... - WCF. .Factory.FromAsync() Begin...() End...(), . .... WCF. Windows Phone 8.

, ( task.Result). , await WP8, . . , "async all the down" . , UI- async var result = await task, var result = task.Result .

+4

, - . Run :

Task<bool> GetTrue()
{
    return Task.Run(() => true);
}

. Result - . Task . Result .

+2

Source: https://habr.com/ru/post/1540152/


All Articles