在C#中了解IAsyncResult请求和线程

时间:2011-10-13 00:15:32

标签: c# .net multithreading asynchronous

上传文件时,我在提交按钮中有以下代码行。因此,请求在后台启动并运行,并告诉用户该文件正在处理。

// Prepare the query string
string arguments = string.Format(
    "?guid={0}&sessionid={1}&seqstring={2}&torrstring={3}", 
    Server.HtmlEncode(_userGuid), Server.HtmlEncode(_guid), 
    Server.HtmlEncode(seqString.ToString()), 
    Server.HtmlEncode(TorRString.ToString()));

// Initialize web request
req = (HttpWebRequest)WebRequest.Create(
    string.Format("{0}{1}", pageUrl.ToString(), arguments));
req.Method = "GET";

// Start the asynchronous request.
IAsyncResult result = (IAsyncResult)req.BeginGetResponse(
    new AsyncCallback(RespCallback), null);

// this line impliments the timeout, if there is a timeout, the callback 
// fires and the request becomes aborted
// ThreadPool.RegisterWaitForSingleObject(
// result.AsyncWaitHandle, 
// new WaitOrTimerCallback(TimeoutCallback), 
// null, DefaultTimeout, true);

为用户提供了响应文件的代码,但有时我认为线程已死并且数据库未更新,因此看起来文件永远不会完成处理。如何判断线程是否仍在运行?用户提交他们的代码,如果我做了结果.IsCompleted;它说结果为空。

2 个答案:

答案 0 :(得分:1)

您可以修改帖子并包含整个按钮点击处理程序以及RespCallbackTimeoutCallback方法吗?这将使您的问题更容易回答。我们需要知道您的网页是否等待WebRequest完成。

我猜你的网页不会等待,但你的代码大多数时间都在工作。如果是这样,WebRequest将与您的正常页面生命周期异步运行。如果页面在WebRequest之前完成,则IIS可以回收应用程序池,并且您的后台请求将被销毁。它大部分时间都可以工作,因为IIS通常不会选择回收,因此WebRequest将继续完成。

答案 1 :(得分:0)

你可能想看一下这个问题,但我会问你为什么在BeginGetResponse结尾处有一个空值而不是传回RequestState。另外,你确定你的数据库调用没有在某个地方失败,你是在指责程序的错误部分吗?

Asynchronous upload using HttpWebRequest