There's no point in using a
BackgroundWorker
for this. It won't make any difference - the browser will be stuck waiting for the response from the server until the server sends the response. Pushing the code that generates the response onto a background thread will just put more strain on the server, without affecting what happens on the client.
If you want the user to be able to continue interacting with your site whilst the Excel file is being generated, you're going to need to make some changes:
- The Excel generation needs to happen in a separate handler - preferably a "generic handler" (
.ashx
file). - The handler which generates the Excel file needs to disable session state. If you don't, other requests from the same session will be blocked until the handler finishes.
- Replace the
<asp:Button>
which currently triggers the download with a <asp:HyperLink>
pointing to the Excel handler. - Set
target="_blank"
on the HyperLink
so that the link opens in a new tab. If you don't, the browser will freeze the current page until the navigation is complete.
This is by no means perfect - the user will see a blank tab whilst the download is being generated, and will have to switch back to the previous tab to continue interacting with your site. If they close the blank tab, the download will be cancelled.
A better option would be to work out
why your export is taking so long, and find a way to speed it up. This would require you to profile your code to find the bottleneck.