I am creating a web application in C#.
When my page loads I fire an asynchronous thread to process some data. Part of this processing is the updating of a cookie. However when I save the cookie to the response by
System.Web.HttpContext.Current.Response.Cookies.Add(cookie)
, I get the following exception:
HttpException: Server cannot modify cookies after HTTP headers have been sent.
Any way I can work around or fix this?
Unless you have a very good reason to, you shouldn't be spinning up background worker threads in an ASP.NET request. Ultimately you still have to wait for this thread to finish its work before you send the response back to the browser.
It sounds like the response stream has already been partially written to and then your thread is trying to add the cookie.
I'd rethink your strategy here and take a read of the following guidelines:
Chapter 6 — Improving ASP.NET Performance - Threading Guidelines
It looks like a dated document but the principles still stand. If the reason for making your call to the data processor is to prevent the ASP.NET worker thread from blocking and using up resources because the data processor is long running, then consider making the page an Asynchronous page instead.