我有一个asp.net控制台应用程序,在这个控制台应用程序中,我想使用WhenAll
以并行方式调用异步方法,这是我的控制台应用程序主方法:
static void Main(string[] args)
{
Marketing ipfd = new Marketing();
try
{
using (WebClient wc = new WebClient()) // call the PM API to get the account id
{
//code goes here...
}
}
catch (Exception e)
{
}
var tasks = ipfd.companies.Select(c => gettingCustomerInfo(c.properties.website.value)).ToList();
var results = await Task.WhenAll(tasks);}
}
这是我调用的方法:-
class Program
{
static int concurrentrequests = int.Parse(ConfigurationManager.AppSettings["ConcurrentRequests"]);
SemaphoreSlim throttler = new SemaphoreSlim(initialCount: concurrentrequests);
int numberofrequests = int.Parse(ConfigurationManager.AppSettings["numberofrequests"].ToString());
int waitduration = int.Parse(ConfigurationManager.AppSettings["waitdurationmilsc"].ToString());
private async Task<ScanInfo> gettingCustomerInfo(string website)
{
await throttler.WaitAsync();
ScanInfo si = new ScanInfo();
var tasks = ipfd.companies.Select(c => gettingCustomerInfo(c.properties.website.value)).ToList();
var results = await Task.WhenAll(tasks);
但我得到了这些例外:-
"await"运算符只能在异步方法中使用。考虑用"async"修饰符标记此方法并更改其返回键入"任务">
非静态字段、方法或属性"***.Program.gettingCustomerInfo(字符串(">
那么有人能对此提出建议吗?现在我知道第一个异常是关于Main方法本身不是异步的,但如果我将Main方法定义为异步的,那么我会得到另一个异常,即程序不包含可以被调用为端点的Main方法?
有两种方法可以绕过这个
首选选项
通过执行以下步骤,使用从C#7.1起可用的新的async Main
支持:
-
编辑您的项目文件以使用C#7.1(属性->构建->高级->选择C#7.1作为您的语言版本(
-
将您的主要方法更改为以下内容:
static async Task Main(string[] args) { ... }
以下是一个演示工作版本的示例项目:
https://github.com/steveland83/AsyncMainConsoleExample
如果感兴趣的话,下面是我写的一组非正式的练习,用来演示处理异步任务的几种方法(以及一些常见的基本错误(:https://github.com/steveland83/async-lab
选项2
如果由于任何原因无法使用上述方法,可以强制异步代码同步运行(请注意,这几乎总是被认为是错误的做法(。
var aggregateTask = Task.WhenAll(tasks);
aggregateTask.Wait();