ASP.net webforms(.NET 2.0)中的异步页面处理示例

Gio*_*lbo 9 asp.net asynchronous webforms

有人可以在ASP.NET Webforms 2.0中为我提供一个简单的异步页面处理示例(我正在使用VS 2010,所以像lambdas这样的新语法可以)吗?

我有一些长时间运行的请求,我不想绑定IIS线程.

为简单起见,假设我当前的代码如下所示:

protected void Page_Load(object sender, EventArgs e)
{
    string param1 = _txtParam1.Text;
    string param2 = _txtParam2.Text;

    //This takes a long time (relative to a web request)
    List<MyEntity> entities = _myRepository.GetEntities(param1, param2);

    //Conceptually, I would like IIS to bring up a new thread here so that I can
    //display the data after it has come back.
    DoStuffWithEntities(entities);

}
Run Code Online (Sandbox Code Playgroud)

如何修改此代码以使其异步?假设我已经在aspx页面中设置了async ="true".

编辑

我想我想出了如何得到我正在寻找的东西.我把示例代码放在这里的答案中.随意指出可以做出的任何缺陷或变化.

Sco*_*man 16

我问过ASP.NET团队的一些人.这是他们给我的电子邮件回复,现在,给你.

最后所做的所有代码都是启动一个新线程并在该线程上执行委托调用.所以现在有两个线程在运行:请求线程和新线程.因此,此示例实际上具有比原始同步代码本来更差的性能.

有关如何在ASP.NET中编写和使用异步方法的示例,请参见http://www.asp.net/web-forms/tutorials/aspnet-45/using-asynchronous-methods-in-aspnet-45.


Ari*_*tos 6

这是异步处理的一个简单示例.

   protected void Page_Load(object sender, EventArgs e)
    {
        ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc));
        ThreadPool.QueueUserWorkItem(state => Dokimes_Programming_multithread_QueryWorkThead.ThreadProc2());

        Debug.Write("Main thread does some work, then sleeps.");
        // If you comment out the Sleep, the main thread exits before
        // the thread pool task runs.  The thread pool uses background
        // threads, which do not keep the application running.  (This
        // is a simple example of a race condition.)
        // Thread.Sleep(4000);

        txtDebug.Text += "ended";

        Debug.Write("end.");
    }


    // This thread procedure performs the task.
    static void ThreadProc(Object stateInfo)
    {

        // No state object was passed to QueueUserWorkItem, so  stateInfo is null.
        Debug.Write(" Hello from the thread pool 1.");
    }

    static void ThreadProc2()
    {
        // No state object was passed to QueueUserWorkItem, so  stateInfo is null.
        Debug.Write("Hello from the thread pool 2.");
    }
Run Code Online (Sandbox Code Playgroud)

另一种方式

您可以使用PageAsyncTask,在这里看到一个完整的例子:
http://msdn.microsoft.com/en-us/library/system.web.ui.pageasynctask.aspx

就像是

clAsynCustomObject oAsynRun = new clAsynCustomObject();

PageAsyncTask asyncTask = new PageAsyncTask(oAsynRun.OnBegin, oAsynRun.OnEnd, oAsynRun.OnTimeout, null, true);
Page.RegisterAsyncTask(asyncTask);
Page.ExecuteRegisteredAsyncTasks();
Run Code Online (Sandbox Code Playgroud)