我最近刚刚遇到 IAsyncResult 并且已经使用了很长一段时间。我真正想知道的是,当我们在那里有更好的替代 ThreadPool 时,为什么要使用 IAsyncResult ?根据我目前对它们的理解,我会选择在几乎所有情况下使用 ThreadPool。所以我的问题是,在任何情况下 IAsyncResult 比另一个更受欢迎吗?
为什么我不喜欢 IAsyncResult:
- BeginXXX 和 EndXXX 增加了复杂性
- 如果调用者不关心返回值,调用者可能会忘记调用 EndXXX
- API 设计中增加的冗余(我们需要为我们想要异步运行的每个方法创建 Begin 和 End 包装器方法)
- 降低可读性
把它放在代码中:
线程池
public void ThreadPoolApproach()
{
ThreadPool.QueueUserWorkItem( ( a ) =>
{
WebClient wc = new WebClient();
var response = wc.DownloadString( "http://www.test.com" );
Console.WriteLine( response );
} );
}
IAsyncResult
public void IAsyncResultApproach()
{
var a = BeginReadFromWeb( ( result ) =>
{
var response = EndReadFromWeb( result );
Console.WriteLine( response );
}, "http://www.test.com" );
}
public IAsyncResult BeginReadFromWeb( AsyncCallback a, string url )
{
var result = new AsyncResult<string>( a, null, this, "ReadFromFile" );
ThreadPool.QueueUserWorkItem( ( b ) =>
{
WebClient wc = new WebClient();
result.SetResult( wc.DownloadString( url ) );
result.Complete( null );
} );
return result;
}
public string EndReadFromWeb( IAsyncResult result )
{
return AsyncResult<string>.End( result, this, "ReadFromFile" );
}