在Azure webjob中进行异步调用后,TextWriter意外关闭

时间:2016-03-09 11:34:17

标签: 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.ObjectDisposedException,如果我对Task.Delay行发表评论,它就可以了! 这是为什么?

1 个答案:

答案 0 :(得分:3)

您需要设置DoJobNow的返回类型以返回任务。调用线程将导致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!");
}