如何将输出值绑定到我的异步 Azure 函数?

How can I bind output values to my async Azure Function?

如何将输出绑定到异步函数?将参数设置为 out 的常用方法不适用于异步函数。

例子

using System;

public static async void Run(string input, TraceWriter log, out string blobOutput)
{
    log.Info($"C# manually triggered function called with input: {input}");
    await Task.Delay(1);

    blobOutput = input;
}

这会导致编译错误:

[timestamp] (3,72): error CS1988: Async methods cannot have ref or out parameters

已使用绑定(仅供参考)

{
  "bindings": [
    {
      "type": "blob",
      "name": "blobOutput",
      "path": "testoutput/{rand-guid}.txt",
      "connection": "AzureWebJobsDashboard",
      "direction": "out"
    },
    {
      "type": "manualTrigger",
      "name": "input",
      "direction": "in"
    }
  ],
  "disabled": false
}

有几种方法可以做到这一点:

将输出绑定到函数的 return 值(最简单)

然后您可以简单地 return 来自函数的值。您必须将输出绑定的名称设置为 $return 才能使用此方法

代码

public static async Task<string> Run(string input, TraceWriter log)
{
    log.Info($"C# manually triggered function called with input: {input}");
    await Task.Delay(1);

    return input;
}

绑定

{
  "bindings": [
    {
      "type": "blob",
      "name": "$return",
      "path": "testoutput/{rand-guid}.txt",
      "connection": "AzureWebJobsDashboard",
      "direction": "out"
    },
    {
      "type": "manualTrigger",
      "name": "input",
      "direction": "in"
    }
  ],
  "disabled": false
}

将输出绑定到 IAsyncCollector

将输出绑定到 IAsyncCollector 并将您的项目添加到收集器。

当您有多个输出绑定时,您将需要使用此方法。

代码

public static async Task Run(string input, IAsyncCollector<string> collection, TraceWriter log)
{
    log.Info($"C# manually triggered function called with input: {input}");
    await collection.AddAsync(input);
}

绑定

{
  "bindings": [
    {
      "type": "blob",
      "name": "collection",
      "path": "testoutput/{rand-guid}.txt",
      "connection": "AzureWebJobsDashboard",
      "direction": "out"
    },
    {
      "type": "manualTrigger",
      "name": "input",
      "direction": "in"
    }
  ],
  "disabled": false
}

异步方法通常可以 return 值,但你不应该 return 值的纯类型,而是使用 Task,如下所示:

 public static async Task<string> Run(string input, TraceWriter log, string blobOutput)
    {
        log.Info($"C# manually triggered function called with input: {input}");
        await Task.Delay(1);

        blobOutput = input;
        return blobOutput;
    }

我还没有资格发表评论,但在上面 Zain Rizvi 的代码中,它应该是 IAsyncCollector:

public static async Task Run(string input, IAsyncCollector<string> collection, 
TraceWriter log)
{
    log.Info($"C# manually triggered function called with input: {input}");
    await collection.AddAsync(input);
}