我想知道如何以"正确"的方式编写自己的异步方法.
我看过许多帖子解释async/await模式,如下所示:
http://msdn.microsoft.com/en-us/library/hh191443.aspx
// Three things to note in the signature:
// - The method has an async modifier.
// - The return type is Task or Task<T>. (See "Return Types" section.)
// Here, it is Task<int> because the return statement returns an integer.
// - The method name ends in "Async."
async Task<int> AccessTheWebAsync()
{
// You need to add a reference to System.Net.Http to declare client.
HttpClient client = new HttpClient();
// GetStringAsync returns a Task<string>. That means …Run Code Online (Sandbox Code Playgroud) 我试图了解如何以及何时使用async编程并进行I/O绑定操作,但我不理解它们.我想从头开始实现它们.我怎样才能做到这一点?
考虑下面的同步示例:
private void DownloadBigImage() {
var url = "https://cosmos-magazine.imgix.net/file/spina/photo/14402/180322-Steve-Full.jpg";
new WebClient().DownloadFile(url, "image.jpg");
}
Run Code Online (Sandbox Code Playgroud)
我如何async通过只使用正常的同步方法DownloadBigImage 来Task.Run实现该版本而不使用,因为这将仅使用线程池中的线程进行等待 - 这只是浪费!
也不要使用已经有的特殊方法async!这就是这个问题的目的:如何在不依赖已经异步的方法的情况下自己制作它?所以,没有像这样的事情:
await new WebClient().DownloadFileTaskAsync(url, "image.jpg");
Run Code Online (Sandbox Code Playgroud)
在这方面非常缺乏可用的示例和文档.我发现只有这个:https: //docs.microsoft.com/en-us/dotnet/standard/async-in-depth ,其中说:
对GetStringAsync()的调用通过较低级别的.NET库(可能调用其他异步方法)调用,直到它到达本机网络库的P/Invoke互操作调用.本机库随后可以调用System API调用(例如对Linux上的套接字的write()).将在本机/托管边界创建任务对象,可能使用TaskCompletionSource.任务对象将通过层传递,可能在操作或直接返回,最终返回到初始调用者.
基本上我必须使用" P/Invoke互操作调用到本机网络库 "......但是如何?