0
我已經實現,這將在應用程序啓動被解僱我的ASP.NET應用程序每n分鐘
using System.Web;
using System.Threading.Tasks;
using System;
using System.Net.Http;
namespace BL.HttpModules
{
public class MyCustomAsyncModule : IHttpModule
{
#region Static Privates
private static bool applicationStarted = false;
private readonly static object applicationStartLock = new object();
#endregion
public void Dispose()
{
}
/// <summary>
/// Initializes the specified module.
/// </summary>
/// <param name="httpApplication">The application context that instantiated and will be running this module.</param>
public void Init(HttpApplication httpApplication)
{
if (!applicationStarted)
{
lock (applicationStartLock)
{
if (!applicationStarted)
{
// this will run only once per application start
this.OnStart(httpApplication);
}
}
}
// this will run on every HttpApplication initialization in the application pool
this.OnInit(httpApplication);
}
public virtual void OnStart(HttpApplication httpApplication)
{
httpApplication.AddOnBeginRequestAsync(OnBegin, OnEnd);
}
private IAsyncResult OnBegin(object sender, EventArgs e, AsyncCallback cb, object extraData)
{
applicationStarted = true;
var tcs = new TaskCompletionSource<object>(extraData);
DoAsyncWork(HttpContext.Current).ContinueWith(t =>
{
if (t.IsFaulted)
{
tcs.SetException(t.Exception.InnerExceptions);
}
else
{
tcs.SetResult(null);
}
if (cb != null) cb(tcs.Task);
});
return tcs.Task;
}
async Task DoAsyncWork(HttpContext ctx)
{
var client = new HttpClient();
var result = await client.GetStringAsync("http://google.com");
// USE RESULT
}
private void OnEnd(IAsyncResult ar)
{
Task t = (Task)ar;
t.Wait();
}
/// <summary>Initializes any data/resources on HTTP module start.</summary>
/// <param name="httpApplication">The application context that instantiated and will be running this module.</param>
public virtual void OnInit(HttpApplication httpApplication)
{
// put your module initialization code here
}
}// end class
}// end namespace
我希望每個5分鐘後火DoAsyncWork的HTTP模塊後,執行異步方法。你能幫助我在那個模塊中實現這個目標嗎?
你知道asp.net中任何類型的計劃任務都是壞主意,不是嗎? –
[以指定的時間間隔定期運行異步方法]可能的重複(https://stackoverflow.com/questions/30462079/run-async-method-regularly-with-specified-interval) – Amy
@Amy我不同意那個特定的重複,這是ASP.NET改變了你如何重複工作的限制這一事實,由於應用程序池的回收,鏈接副本中的兩個解決方案都無法在ASP.NET上長期運行。 –