异步执行返回页面内容 AddOnPreRenderCompleteAsync

aspx: Async="true"
<%@ Page Language="C#" Async="true" AutoEventWireup="true" CodeFile="AsynCall.aspx.cs" Inherits="AsynCall" %>


cs:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;

public partial class AsynCall : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// 准备回调数据,它将由AddOnPreRenderCompleteAsync的第三个参数被传入。 
AsyncDemo handler = new AsyncDemo("test1");

// 注册一个异步任务。注意这三个参数哦。 
AddOnPreRenderCompleteAsync(BeginCall, EndCall, handler); 
}

private IAsyncResult BeginCall(object sender, EventArgs e, AsyncCallback cb, object extraData)
{
// 在这个方法中, 
// sender 就是 this 
// e 就是 EventArgs.Empty 
// cb 就是 EndCall 
// extraData 就是调用AddOnPreRenderCompleteAsync的第三个参数 
AsyncDemo handler = (AsyncDemo)extraData;

// 开始一个异步调用。页面线程也最终在执行这个调用后返回线程池了。 
// 如果网络调用完成,则会调用 cb 对应的回调委托,其实就是下面的方法 
IAsyncResult ret = handler.BeginRun(cb, handler);
return ret;
}

private void EndCall(IAsyncResult ar)
{
// 到这个方法中,表示一个任务执行完毕。 
// 参数 ar 就是BeginCall的返回值。 

Trace.Write("EndCall ThreadId = " + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString());

AsyncDemo handler = (AsyncDemo)ar.AsyncState;

try
{
Response.Write("success: " + handler.EndRun(ar));
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}

public class AsyncDemo
{
// Use in asynchronous methods 
private delegate string runDelegate();

private string m_Name;
private runDelegate m_Delegate;

public AsyncDemo(string name)
{
m_Name = name;
m_Delegate = new runDelegate(Run);
}

/**/
/// <summary> 
/// Synchronous method 
/// </summary> 
/// <returns></returns> 
public string Run()
{
Thread.Sleep(3 * 1000);
return "My name is " + m_Name;
}

/**/
/// <summary> 
/// Asynchronous begin method 
/// </summary> 
/// <param name="callBack"></param> 
/// <param name="stateObject"></param> 
/// <returns></returns> 
public IAsyncResult BeginRun(
AsyncCallback callBack, Object stateObject)
{
try
{
return m_Delegate.BeginInvoke(callBack, stateObject);
}
catch (Exception e)
{
// Hide inside method invoking stack 
throw e;
}
}

/**/
/// <summary> 
/// Asynchronous end method 
/// </summary> 
/// <param name="ar"></param> 
/// <returns></returns> 
public string EndRun(IAsyncResult ar)
{
if (ar == null)
throw new NullReferenceException(
"Arggument ar can't be null");

try
{
return m_Delegate.EndInvoke(ar);
}
catch (Exception e)
{
// Hide inside method invoking stack 
throw e;
}
}
} 

}


同一个session是单线程运行的run函数
不同session,run是可以多线程执行的。


就效率而言和直接在aspx同步做,没多少区别。
要高效,还是用ManualResetEvent高些,访问aspx的时候,创建event,wait,别的线程处理完数据,事件通知完成,并返回结果到缓存里面。
http协议对于及时通讯效率肯定低,websocket协议要高效些,类似tcp了。

你可能感兴趣的:(c#)