如何将输出值绑定到异步Azure功能?

Zai*_*zvi 15 c# asynchronous azure azure-functions

如何将输出绑定到异步函数?设置参数的常用方法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;
}
Run Code Online (Sandbox Code Playgroud)

这导致编译错误:

[timestamp] (3,72): error CS1988: Async methods cannot have ref or out parameters
Run Code Online (Sandbox Code Playgroud)

使用绑定(fyi)

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

Zai*_*zvi 15

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

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

然后,您只需返回函数中的值即可.您必须将输出绑定的名称设置$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;
}
Run Code Online (Sandbox Code Playgroud)

捆绑

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

将输出绑定到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);
}
Run Code Online (Sandbox Code Playgroud)

捆绑

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