According to literature I've read about QueueBackgroundWorkItem, I should be able to complete a long task in the background without being interrupted by IIS.
What I'm wondering if is possible, if I start a long task and close my website before it completes, shouldn't the QueueBackgroundWorkItem finish the task? (it's not currently)
Here are my calls:
private async Task WriteTextAsync(CancellationToken cancellationToken)
{
string filePath = printPath;
string text;
byte[] encodedText = Encoding.Unicode.GetBytes(text);
for (int i = 0; i < 200; i++)
{
text = "Line " + i + "\r\n";
encodedText = Encoding.Unicode.GetBytes(text);
using (FileStream sourceStream = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true))
{
await sourceStream.WriteAsync(encodedText, 0, encodedText.Length);
};
Thread.Sleep(200);
}
}
private void QueueWorkItem()
{
Func<CancellationToken, Task> workItem = WriteTextAsync;
HostingEnvironment.QueueBackgroundWorkItem(workItem);
}
EDIT: I have gotten this to work. I trimmed it up. This now executes after the browser is closed, about 3-4 minutes, everything is written to file. Thanks for all who chipped in.
private void QueueWorkItem()
{
HostingEnvironment.QueueBackgroundWorkItem(cancellationToken =>
{
string filePath = printPath;
string text = "File line ";
TextWriter tw = new StreamWriter(printPath);
for (int i = 0; i < 400; i++)
{
text = "Line " + i;
tw.WriteLine(text);
Thread.Sleep(200);
}
tw.Close();
});
}