使用 Microsoft 异步框架的基础知识
使用 Visual Studio Async CTP(版本 3),我很难理解如何使用此框架“包装”现有代码。
例如,
使用 OpenPop.NET 库,我尝试与 pop3 服务器建立连接,并确认我拥有有效的用户名和密码。
假设我有一些这样的代码。
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;
}
现在我想让它异步,根据我一直在阅读和拼凑的内容,我的理解是我最终会得到一个方法签名,
public async Task<bool> ConnectAsync()
{
}
我相信这是正确的签名,因为它将是一个返回布尔值的任务(?)我的猜测是我需要使用 TaskEx.Run() 方法?但这是我所能想到的。有人能指出正确的方向吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,到目前为止你是对的。
正如您所说,转换方法的简单方法是将其包装在
TaskEx.Run
中,以便该方法在线程池线程上运行,并且不会阻塞您的 UI 线程。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.从根本上讲,为了从异步 CTP 中获得最大收益,您实际上可以一直使用异步调用。您可以非常轻松地将同步
ConnectSync
方法包装在任务中,而无需使用异步 CTP:(您可能不必在此处指定类型参数- 我永远记不起使用方法组转换进行类型推断的确切规则。)
但这仍然会在连接时占用线程。如果您对此表示同意,那么至少您最终会得到一个可以从异步方法调用并适当等待的方法。如果不出意外,这将允许您使用异步向上构建应用程序的其余部分,然后如果/当 POP3 代码支持异步时,您可以将
ConnectAsync
重写为异步方法。Fundamentally, in order to reap the most benefits from the async CTP you could really do with async calls all the way down. You can wrap your synchronous
ConnectSync
method in a task very easily, without using the async CTP at all:(It's possible that you don't have to specify the type argument here - I can never remember the exact rules for type inference using method group conversions.)
That will still tie up a thread while it's connecting though. If you're okay with that, then at least you'll end up with a method you can call from an async method and await appropriately. If nothing else, this will allow you to build the rest of your application upwards using async, and then if/when the POP3 code supports async, you can just rewrite
ConnectAsync
to be an async method.