Peyman
Peyman

Reputation: 3077

Issue using Task.Factory.FromAsync

I enjoyed the new C# 5's async and await and I want to set it up to one of my previous Tcp application which I used the async whay (not async & await, in fact Begin*, End*)

in my application every message have a response, so every time you use BeginSend, you will receive a message related the message you first sent. (lets suppose command and it's report)

I want to add a new function called RequestAsync that you send your message and wait till the response comes. let me show the usage

string response = await RequestAsync("hi");

on this occasion, you will send a "hi" message and then code waits till the response related to this comes.

I had problems using Task.Factory.FromAsync, so I tried the following code, i want to make sure the performance is roughly the same as TaskFactory way.

public async Task<IRequestResult> SendRequestAsync(IRequest request, string message)
{
        IRequestResult result = BeginSendRequest(request, message);

        while (!result.IsCompleted)
        {
            await Task.Delay(1);
        }

        return result;
}

and BeginRequest is my own method.

Sincerely yours, Peyman Mortazavi

Upvotes: 0

Views: 1036

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500055

No, that's going to be pretty awful in terms of efficiency - you'll be waking up and requiring rescheduling every 5 milliseconds. You've added latency while you effectively sleep between cycles as well.

You should go back to trying to use Task.Factory.FromAsync - you haven't told us what went wrong when you tried that, so it's hard to help you fix it... It's possible that you haven't implemented the asynchronous programming model pattern correctly to start with. (The fact that you're not providing a callback to your BeginSendRequest method is suggestive of that.)

I hope your real code doesn't have catch {} either...

Upvotes: 4

Nikola Bogdanović
Nikola Bogdanović

Reputation: 3213

Poling can never be efficient as IO completion ports, and why even use an async method if you are only waiting for it and not doing anything in the mean time, it just ads needles overhead.

Upvotes: 0

Related Questions