2

I've created a simple Azure WebJob that calls an async Task and am trying to use the TextWriter to log some information. Writing to the log before the call to the async task is fine but after the call the TextWriter is closed. In the sample code below, I am just calling Task.Delay() to demonstrate.

It does not matter if I change the await log.WriteLineAsync("") calls to 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!");

    }
}

When I run this code locally, I get a System.ObjectDisposedException on the last log call and if I comment on the Task.Delay line, it works fine! Why is this?

Catch22
  • 3,261
  • 28
  • 34
  • possible duplicate: http://stackoverflow.com/questions/31507384/azure-webjob-textwritter-logger-being-disposed-in-the-middle-of-my-method – Jakub Szumiato Mar 09 '16 at 12:00

1 Answers1

3

You need to set the return type of DoJobNow to return a Task. The calling thread will cause the TextWriter to be disposed

[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!");
}
InitLipton
  • 2,395
  • 5
  • 30
  • 47