[
  {
    "Id": "1086271",
    "ThreadId": "454884",
    "Html": "Hello,\r<br />\n<br />\nI am having trouble implementing a threaded version of the Response.OutputStream example.\r<br />\n<br />\nAll runs well as non-threaded, however, when I try to call the same method(downloadArchiveThread) via ThreadPool.QueueUserWorkItem or spin up my our thread(StartBackgroundThread), the resulting zip file is 'invalid'.  My code listed below.<br />\n\r<br />\nMy goal is to free up the browser on larger zip file downloads as the non-threaded implementation ties up the browser user interface until the download is complete.\r<br />\n<br />\nThank you.\r<br />\n<br />\n<br />\npublic void downloadArchive(Object sender, EventArgs e)\r<br />\n{<br />\n<pre><code>try\n{\n    string filename = txtName.Text + &quot;.zip&quot;;\n    string dirPath = myDirPath;\n\n    downloadArchiveThread(dirPath, txtName.Text, folderName);  // works perfectly, except ties up browser\n    //ThreadPool.QueueUserWorkItem(o =&gt; downloadArchiveThread(dirPath, txtName.Text, folderName));  // 'invalid' zip file downloaded\n    //StartBackgroundThread(delegate { downloadArchiveThread(dirPath, txtName.Text, folderName); }); // 'invalid' zip file downloaded\n}\ncatch (Exception ex) { throw (ex); }</code></pre>\n\n}\r<br />\n<br />\npublic void downloadArchiveThread( string dirPath, string baseFileName, string folderName)\r<br />\n{<br />\n<pre><code>Response.Clear();\nResponse.BufferOutput = false;  // for large files\nResponse.ContentType = &quot;application/zip&quot;;\nstring fileName = baseFileName + &quot;.zip&quot;;\nResponse.AddHeader(&quot;content-disposition&quot;, &quot;filename=&quot; + fileName);\n\nlock (objLock){\n\n    try\n    {\n        using (ZipFile zip = new ZipFile())\n        {\n            zip.AddDirectory(dirPath, folderName);\n            zip.Save(Response.OutputStream);\n        }\n    }\n    catch (Exception ex) { Response.Write(&quot;error: &quot; + ex.Message); Response.Close(); }\n\n    if (!Response.IsClientConnected)\n    {\n        Response.Close();\n    }\n\n}\n</code></pre>\n\n}\r<br />\n<br />\n<br />\npublic static void StartBackgroundThread(ThreadStart threadStart)\r<br />\n{<br />\n<pre><code>if (threadStart != null)\n{\n    Thread thread = new Thread(threadStart);\n    thread.IsBackground = true;\n    thread.Start();\n}</code></pre>\n\n}<br />\n",
    "PostedDate": "2013-08-29T10:03:21.533-07:00",
    "UserRole": null,
    "MarkedAsAnswerDate": null
  }
]