Using Visual Studio Async CTP (Version 3) I am struggling to understand how I can "wrap" existing code using this framework.
For example
Using the OpenPop.NET library I am trying to establish a connection with a pop3 server and confirm I have a valid username and password.
So lets say I have some code like this.
public bool ConnectSync()
{
bool success = true;
Pop3Client client = new Pop3Client();
try
{
client.Connect("mail.server.com", 110, false);
client.Authenticate("username", "password");
}
catch
{
success = false;
}
return success;
}
And now I want to make it Async my understanding from what I have been reading and piecing together is that I would end up with a method signature along the lines of
public async Task<bool> ConnectAsync()
{
}
I believe this is the correct signature because it will be a task that returns a boolean(?) and my guess is that I will need to utilize the TaskEx.Run() method? but that's as far as I can seem to get my head around. Could anyone point in the right direction?
Yes, you're right so far.
The easy way to convert your method is, as you say, just to wrap it in TaskEx.Run
so the method runs on a thread pool thread and doesn't block your UI thread.
public Task<bool> ConnectAsync()
{
return TaskEx.Run( () =>
{
bool success = true;
Pop3Client client = new Pop3Client();
try
{
client.Connect("mail.server.com", 110, false);
client.Authenticate("username", "password");
}
catch
{
success = false;
}
return success;
}
);
}