我有一个名为async
的{{1}} Web API,用于从Azure中托管的API读取一些数据,处理它并将其保存在SQL服务器中。我已将MyCustomAPI
Web API , Azure API 和调用SQL服务器作为MyCustomAPI
调用。我必须在命令行应用程序中调用调用Web API方法async
的{{1}}。
我遇到的问题是我无法在ReadAndSaveDataCalleeAsync
方法中进行MyCustomAPI.ReadAndSaveDataAsync()
次调用。我必须使用Async
方法进行调用。这将使Main
方法等待,因此请将其同步。
Wait()
我认为这打败了制作(1)MyCustomerAPI(2)Azure API(3)数据库调用Main
的目的。我的理解是,我必须进行所有调用static void Main()
{
ReadAndSaveDataCalleeAsync().Wait(); // Calls MyCustomAPI.ReadAndSaveDataAsync
}
以获得操作系统的好处,非常有效地处理所有方法的资源和线程。
如何让命令行应用async
获得所有其他服务async
功能的好处?
答案 0 :(得分:1)
您调用API的方法应该有async
修饰符,返回类型应为Task
或Task<T>
,如MSDN中的示例所示:
// 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 that when you await the
// task you'll get a string (urlContents).
Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com");
// You can do work here that doesn't rely on the string from GetStringAsync.
DoIndependentWork();
// The await operator suspends AccessTheWebAsync.
// - AccessTheWebAsync can't continue until getStringTask is complete.
// - Meanwhile, control returns to the caller of AccessTheWebAsync.
// - Control resumes here when getStringTask is complete.
// - The await operator then retrieves the string result from getStringTask.
string urlContents = await getStringTask;
// The return statement specifies an integer result.
// Any methods that are awaiting AccessTheWebAsync retrieve the length value.
return urlContents.Length;
}