【问题标题】:How can I run a 'async' operation in a C# command line application? [duplicate]如何在 C# 命令行应用程序中运行“异步”操作? [复制]
【发布时间】:2017-08-18 20:00:00
【问题描述】:

我有一个名为 MyCustomAPIasync Web API,用于从托管在 Azure 中的 API 读取一些数据,对其进行处理并将其保存在 SQL 服务器中。我已将MyCustomAPI Web APIAzure APISQL 服务器调用 设为async 调用。我必须在命令行应用程序中调用调用 Web API 方法 MyCustomAPI.ReadAndSaveDataAsync()ReadAndSaveDataCalleeAsync

我遇到的问题是我无法在Main 方法中进行Async 调用。我必须用Wait() 方法打电话。这将使Main 方法等待,因此使其同步。

static void Main()
{
  ReadAndSaveDataCalleeAsync().Wait(); // Calls MyCustomAPI.ReadAndSaveDataAsync
}

我认为这违背了 (1) MyCustomerAPI (2) Azure API (3) 数据库调用 async 的目的。我的理解是,我必须进行所有调用 async 才能获得操作系统的好处,从而非常有效地处理所有方法的资源和线程。

如何使命令行应用程序async 受益于所有其他服务async 功能?

【问题讨论】:

  • 异步的主要好处是您的网络服务器没有阻塞线程。如果你想对它做任何事情,你显然必须在控制台应用程序中等待结果。
  • 你在程序中还做了什么?
  • 命令行进程在退出 Main 方法后结束——关闭所有关联的进程/线程。所以如果你让它等待,它会在异步进程完成之前关闭它。说“这是设计使然,有充分的理由,而且可能是你想要的,无论如何”,这是一段很长的路要走。
  • 由于目前还不清楚您正在寻找什么好处,因此帖子听起来像是标准“异步和命令行”帖子的完美副本。如果这些帖子没有回答您的问题,请务必说明您希望通过使用异步方法在命令行应用程序中获得哪些好处。

标签: c# async-await command-prompt


【解决方案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

【讨论】:

  • 虽然这根本不能回答问题,但它包含一条有用的信息(所以不要反对)。
猜你喜欢
  • 2021-08-14
  • 2017-02-26
  • 2018-11-06
  • 1970-01-01
  • 1970-01-01
  • 2015-11-21
  • 1970-01-01
  • 1970-01-01
  • 2020-11-20
相关资源
最近更新 更多