我有一个异步操作,由于各种原因,需要使用对ASP.NET网页的HTTP调用来触发该操作.当我的页面被请求时,它应该启动此操作,并立即向客户端返回确认.

该方法也是通过WCF Web服务公开的,它可以完美地工作.

在我第一次try 时,抛出了一个异常,告诉我:

Asynchronous operations are not allowed in this context.
Page starting an asynchronous operation has to have the Async
attribute set to true and an asynchronous operation can only be
started on a page prior to PreRenderComplete event.

当然,我在@Page指令中添加了Async="true"参数.现在,我没有收到任何错误,但是在异步操作完成之前,页面一直处于阻塞状态.

我怎样才能得到一个真正的火焰而忘记页面工作?

Edit:一些代码以获取更多信息.这比这要复杂一点,但我已经试着把大概的 idea 写进go 了.

public partial class SendMessagePage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string message = Request.QueryString["Message"];
        string clientId = Request.QueryString["ClientId"];

        AsyncMessageSender sender = new AsyncMessageSender(clientId, message);
        sender.Start();

        Response.Write("Success");
    }
}

AsyncMessageSender类:

public class AsyncMessageSender
{
    private BackgroundWorker backgroundWorker;
    private string client;
    private string msg;

    public AsyncMessageSender(string clientId, string message)
    {
        this.client = clientId;
        this.msg = message;

        // setup background thread to listen
        backgroundThread = new BackgroundWorker();
        backgroundThread.WorkerSupportsCancellation = true;
        backgroundThread.DoWork += new DoWorkEventHandler(backgroundThread_DoWork);
    }

    public void Start()
    {
        backgroundThread.RunWorkerAsync();
    }

    ...
    // after that it's pretty predictable
}

推荐答案

如果您不关心向用户返回任何内容,您可以只启动一个单独的线程,或者使用委托并异步调用它,这是一种快速而肮脏的方法.如果您不在乎在异步任务完成时通知用户,可以忽略回调.try 将断点放在SomeVeryLongAction()方法的末尾,您将看到它在页面提供后结束运行:

private delegate void DoStuff(); //delegate for the action

protected void Page_Load(object sender, EventArgs e)
{

}

protected void Button1_Click(object sender, EventArgs e)
{
    //create the delegate
    DoStuff myAction = new DoStuff(SomeVeryLongAction); 
    //invoke it asynchrnously, control passes to next statement
    myAction.BeginInvoke(null, null);
    Button1.Text = DateTime.Now.ToString();
}


private void SomeVeryLongAction()
{
    for (int i = 0; i < 100; i++)
    {
        //simulation of some VERY long job
        System.Threading.Thread.Sleep(100);
    }
}

Asp.net相关问答推荐

更新剃须刀页面中图表的值

Web API Queryable - 如何应用 AutoMapper?

如何在 GridView 单元格中的(即
)中呈现解码的 HTML

asp.net、url 重写模块和 web.config

指定的 CGI 应用程序遇到错误,服务器终止了进程

ASP.NET Response.Redirect 使用 302 而不是 301

为什么 ASP.NET Identity 2.0 使用 GUID/字符串作为用户 ID?

使用 IIS 的 ASP.NET 调试超时

用于链接字符串中的 url 的 C# 代码

如何更改 .ASPX 自动格式化设置 (Visual Studio)

Request.Params 和 Request.Form 什么时候不同?

HTTP 错误 503.该服务在简单的 ASP.NET 4.0 网站下不可用

在 ASP.NET 中将虚拟路径转换为实际 Web 路径

在 Android/Java 和 C# 中计算 SHA256 哈希

Web.Config 中的 Assemblies node 的用途是什么?

如何将表从存储过程检索到数据表?

人们使用 JScript.Net 的目的是什么?

Docker 中的 ASPNETCORE_ENVIRONMENT

字体真棒里面asp按钮

如何清除 System.Runtime.Caching.MemoryCache