我有这个功能
[FunctionName("Func")]
public async Task Run(
[TimerTrigger("1 1 8-23 * * 1-5")] TimerInfo timerInfo,
[Blob("metrics/accepted.json", FileAccess.Read, Connection = "AzureWebJobsStorage")] string json,
[Blob("metrics/accepted.json", FileAccess.Write, Connection = "AzureWebJobsStorage")] Stream outputFile,
ILogger log
)
{
string out = await doThing(json);
if (out != "") {
byte[] byteArray = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(resp));
await outputFile.WriteAsync(byteArray, 0, byteArray.Length);
}
}
添加断点后,文件填充流时被清空? 有什么办法可以防止这种情况发生吗?
添加断点后,文件填充流时被清空?有什么办法可以防止这种情况发生吗?
您面临的问题,因为您尝试在同一个文件上读取和写入,这导致了并发问题,并且由于输出绑定覆盖了文件的内容,文件的数据被清空。
您需要将其写入不同的文件中。
这段代码对我有用。
Function1.cs
using System;
using System.IO;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace FunctionApp3
{
public class Function1
{
[FunctionName("Function1")]
public static async Task Run([TimerTrigger("0 */5 * * * *")] TimerInfo myTimer,
[Blob("metrics/accepted.json", FileAccess.Read, Connection = "AzureWebJobsStorage")] Stream json,
[Blob("metrics/accepted2.json", FileAccess.Write, Connection = "AzureWebJobsStorage")] Stream outputFile,
ILogger log)
{
log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
JsonModel jsonObject;
using (var reader = new StreamReader(json))
{
var jsonContent = await reader.ReadToEndAsync();
log.LogInformation($"content of accepted.json : {jsonContent}");
jsonObject = JsonConvert.DeserializeObject<JsonModel>(jsonContent);
jsonObject.Platform = "StackOverflow";
}
byte[] byteArray = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(jsonObject, Formatting.Indented));
await outputFile.WriteAsync(byteArray,0,byteArray.Length);
}
public class JsonModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Platform { get; set; }
}
}
}
OUTPUT
:
accepted.json:
{
"FirstName": "Vivek",
"LastName": "Shandilya"
}
Functions:
Function1: timerTrigger
For detailed output, run func with --verbose flag.
[2024-01-24T07:00:57.091Z] Executing 'Function1' (Reason='Timer fired at 2024-01-24T12:30:54.2878940+05:30', Id=56819861-b602-447c-82ea-5dab57849da1)
[2024-01-24T07:00:57.097Z] Trigger Details: UnscheduledInvocationReason: IsPastDue, OriginalSchedule: 2024-01-24T12:10:00.0000000+05:30
[2024-01-24T07:00:57.172Z] C# Timer trigger function executed at: 1/24/2024 12:30:57 PM
[2024-01-24T07:00:57.490Z] content of accepted.json : {
[2024-01-24T07:00:57.494Z] "FirstName":"Vivek",
[2024-01-24T07:00:57.499Z] "LastName":"Shandilya"
[2024-01-24T07:00:57.503Z] }
[2024-01-24T07:00:57.665Z] Host lock lease acquired by instance ID '000000000000000000000000AAE5F384'.
[2024-01-24T07:00:58.538Z] Executed 'Function1' (Succeeded, Id=56819861-b602-447c-82ea-5dab57849da1, Duration=4181ms)
accepted2.json:
{
"FirstName": "Vivek",
"LastName": "Shandilya",
"Platform": "StackOverflow"
}