如何在C#命令行应用程序中运行“异步”操作?

时间:2017-03-26 01:21:35

标签: c# async-await command-prompt

我有一个名为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功能的好处?

1 个答案:

答案 0 :(得分:1)

您调用API的方法应该有async修饰符,返回类型应为TaskTask<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;  
}  

这是链接:https://msdn.microsoft.com/en-us/library/mt674882.aspx