无法在我的asp.net控制台应用程序中调用异步和并行方法

时间:2018-11-29 15:34:16

标签: c# asp.net async-await task

我有一个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”运算符只能在异步方法中使用。考虑   使用“异步”修饰符标记此方法并更改其返回值   输入“任务”

     

非静态字段,方法或   属性'***。Program.gettingCustomerInfo(string)'

那么有人可以对此提出建议吗?现在我知道第一个例外是关于Main方法本身不是异步的,但是如果我将main方法定义为异步的,那么我将得到另一个例外,该程序不包含可以称为端点的Main方法?

1 个答案:

答案 0 :(得分:1)

有两种方法可以解决这个问题

首选选项

通过执行以下步骤,使用C#7.1中自async Main起新可用的支持:

  • 编辑您的项目文件以使用C#7.1(“属性->构建->高级->选择C#7.1作为您的语言版本)

  • 将Main方法更改为以下内容:

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();