Ho un'operazione asincrona che per vari motivi deve essere attivata utilizzando una chiamata HTTP a una pagina Web ASP.NET. Quando viene richiesta la mia pagina, dovrebbe iniziare questa operazione e restituire immediatamente un riconoscimento al client.Esecuzione di un'operazione asincrona attivata da una richiesta di una pagina Web ASP.NET
Questo metodo è anche esposto tramite un servizio Web WCF e funziona perfettamente.
Al mio primo tentativo, un'eccezione è stato gettato, dicendomi:
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.
Così, naturalmente, ho aggiunto il parametro Async="true"
alla direttiva @Page
. Ora, non ricevo un errore, ma la pagina sta bloccando fino al completamento dell'operazione asincrona.
Come si attiva una vera e semplice pagina di attivazione e disattivazione?
Modifica: Alcuni codici per ulteriori informazioni. È un po 'più complicato di così, ma ho cercato di ottenere l'idea generale.
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");
}
}
La classe 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
}
Difficile rispondere senza visualizzare il codice che chiama questa operazione asincrona. – Bryan
Ok, aggiornerò la domanda con maggiori informazioni. Grazie. – Damovisa
In Azure, è possibile utilizzare i lavori Web. Vedere http://curah.microsoft.com/52143/using-the-webjobs-feature-of-windows-azure-web-sites I thread in background su ASP.NET sono problematici. – RickAndMSFT