user1399653
user1399653

Reputation: 193

Task.Factory.FromAsync call runs synchronously

I am using Task.Factory.FromAsync to publish a message (to rabbitmq) asynchronously. The following code seems to run synchronously. "End of main" line is displayed on the console after "In begin publish method".

SHouldn't the control be returned to the main thread and "End Of Main" be displayed when the code "awaits" at Task.Factory.FromAsync?

    private async void TestAsync()
    {
        int x = await TryAsync();
        Console.WriteLine("End of Main");
    }

    async static Task<int> TryAsync()
    {

        await Task.Factory.FromAsync(BeginPublish("This is message", new AsyncCallback(GetPublishResult), null), EndPublish);

        return 1;
    }


    public static IAsyncResult BeginPublish(string message, AsyncCallback callback, object state)
    {

        TaskCompletionSource<int> t = new TaskCompletionSource<int>();

       //Simulate call to rabbitmq
        Thread.Sleep(2000);

        Console.WriteLine("In begin publish method");

        return t.Task;
    }

    private static void EndPublish(IAsyncResult asyncResult)
    {
        Thread.Sleep(2000);

        Console.WriteLine("End Publish method completed");
    }

Upvotes: 1

Views: 551

Answers (1)

Servy
Servy

Reputation: 203812

The following code seems to run synchronously. "End of main" line is displayed on the console after "In begin publish method".

That's correct. The main method cannot continue execution until it has finished starting the Task. Your BeginPublish method is meant to start the task, and return as quickly as possible, letting all of the work happen without blocking. The caller isn't able to continue execution until it is given the IAsyncResult that the method returns.

Upvotes: 2

Related Questions