如何将输出绑定到异步函数?将参数设置为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
使用绑定(fyi)
{
"bindings": [
{
"type": "blob",
"name": "blobOutput",
"path": "testoutput/{rand-guid}.txt",
"connection": "AzureWebJobsDashboard",
"direction": "out"
},
{
"type": "manualTrigger",
"name": "input",
"direction": "in"
}
],
"disabled": false
}
答案 0 :(得分:14)
有几种方法可以做到这一点:
然后您只需返回函数中的值即可。您必须将输出绑定的名称设置为$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并将您的项目添加到收集器。
当您有多个输出绑定时,您将要使用此方法。
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
}
答案 1 :(得分:2)
我还没有声誉可以发表评论,但在上面的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);
}
答案 2 :(得分:0)
异步方法可以正常返回值,但是你不应该返回纯类型的值,而是使用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;
}