我有一个asp.net webform,它写了大约25-30个项目(当用户从表单提出后续请求时需要信息)到自定义缓存中。目前所有这些都在主线程上同步发生。但是在更高的负载下,addcache正成为瓶颈。
如何在后台运行此任务而不使用asp.net工作进程线程池中的线程。
答案 0 :(得分:4)
备选方案:
从客户端使用AJAX调用服务器代码,并添加代码以监控调用过程
我刚刚添加了与此过程相关的答案:
从客户端到服务器的调用将是同步的,这意味着响应将不会返回到客户端,直到整个过程结束,但真正的代码将执行async释放ASP.Net使用的线程增加可伸缩性
执行页面异步。您需要在后面的ASPX代码中实现IHttpAsyncHandler
接口。这是一个例子:
public partial class _Default : System.Web.UI.Page, IHttpAsyncHandler
{
public void EndProcessRequest(IAsyncResult result)
{
var context = (result as AsyncOperation).Context;
context.Response.Write(string.Format("<p>End Process Request on {0}</p>", Thread.CurrentThread.ManagedThreadId.ToString()));
}
public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
{
var operation = new AsyncOperation(cb, this.Context, extraData);
operation.StartAsync();
this.Context.Response.Write(string.Format("<p>Begin Process Request on: {0}...</p>", Thread.CurrentThread.ManagedThreadId.ToString()));
return operation;
}
}
public class AsyncOperation : IAsyncResult
{
private AsyncCallback asyncCallback;
public AsyncOperation(AsyncCallback asyncCallback, HttpContext context, object state)
{
this.AsyncState = state;
this.asyncCallback = asyncCallback;
this.Context = context;
this.IsCompleted = false;
this.AsyncWaitHandle = null;
this.CompletedSynchronously = false;
}
public HttpContext Context { get; private set; }
public object AsyncState { get; private set; }
public WaitHandle AsyncWaitHandle { get; private set; }
public bool CompletedSynchronously { get; private set; }
public bool IsCompleted { get; private set; }
public void StartAsync()
{
ThreadPool.QueueUserWorkItem(new WaitCallback(StartAsyncOperation), this.AsyncState);
}
public void StartAsyncOperation(object workItemState)
{
// place here the async logic
this.Context.Response.Write(string.Format("<p>Long Async operation started on: {0}</p>", Thread.CurrentThread.ManagedThreadId.ToString()));
Thread.Sleep(2000);
this.Context.Response.Write(string.Format("<p>Long Async operation ended on: {0}</p>", Thread.CurrentThread.ManagedThreadId.ToString()));
this.IsCompleted = true;
this.asyncCallback(this);
}
}
<强>输出强>
创建一个HttpAsyncHandler。您需要创建实现HttpHandler
接口的自定义IHttpAsyncHandler
。例如:
public class AsyncHandler : IHttpAsyncHandler
{
public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
{
var operation = new AsyncOperation(cb, context, extraData);
operation.StartAsync();
context.Response.Write(string.Format("<p>Begin Process Request on: {0}...</p>", Thread.CurrentThread.ManagedThreadId.ToString()));
return operation;
}
public void EndProcessRequest(IAsyncResult result)
{
var context = (result as AsyncOperation).Context;
context.Response.Write(string.Format("<p>End Process Request on {0}</p>", Thread.CurrentThread.ManagedThreadId.ToString()));
}
public bool IsReusable
{
get { return false; }
}
public void ProcessRequest(HttpContext context)
{
throw new NotImplementedException();
}
}