c# - Azure Web 作业中的异步调用后 TextWriter 意外关闭

标签 c# async-await azure-webjobs

我创建了一个简单的 Azure WebJob,它调用异步任务,并尝试使用 TextWriter 来记录一些信息。 在调用异步任务之前写入日志没问题,但在调用之后,TextWriter 将关闭。在下面的示例代码中,我只是调用 Task.Delay() 来演示。

如果我将 await log.WriteLineAsync("") 调用更改为 log.WriteLine("")

也没关系
public class Program
{
    // Please set the following connection strings in app.config for this WebJob to run:
    // AzureWebJobsDashboard and AzureWebJobsStorage
    static void Main()
    {
        JobHostConfiguration config = new JobHostConfiguration();
        JobHost host = new JobHost(config);
        host.Call(typeof (Program).GetMethod("DoJobNow"), new { value = "Hello world!" });
        host.RunAndBlock();
    }


    [NoAutomaticTrigger]
    public async static void DoJobNow(string value, TextWriter log)
    {
        await log.WriteLineAsync("Write with textwriter");
        await log.WriteLineAsync("Write with textwriter again - still open");
        await Task.Delay(100);
        await log.WriteLineAsync("TextWriter is closed?? Exception here!");

    }
}

当我在本地运行此代码时,我在最后一次日志调用中收到 System.ObjectDisposeException ,如果我对 Task.Delay 行进行评论,它工作正常! 这是为什么?

最佳答案

您需要设置DoJobNow的返回类型以返回Task。调用线程将导致 TextWriter 被释放

[NoAutomaticTrigger]
public async static Task DoJobNow(string value, TextWriter log)
{
    await log.WriteLineAsync("Write with textwriter");
    await log.WriteLineAsync("Write with textwriter again - still open");
    await Task.Delay(100);
    await log.WriteLineAsync("TextWriter is closed?? Exception here!");
}

关于c# - Azure Web 作业中的异步调用后 TextWriter 意外关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35890474/

相关文章:

javascript - 尝试在我的代码中使用 await with promise - 怎么做?

azure - 是否可以将更改源处理器主机作为 Azure Web 作业运行?

Azure WebJob 部署不断失败

c# - 在 html 文本框 mvc 中使用短日期字符串

c# - 如何检查是否已抛出任何异常?

javascript - Node.js 将数据返回到异步函数失败

c# - Azure 移动服务客户端 - 在多个 InsertAsync 任务上使用 WaitAll

c# - Azure Web 作业 - 保存应用程序设置以在重新启动后保留

c# - 在 DataGridView C# 中复制项目

c# - COMException 故障