Я пытаюсь добавить ускорение скорости к HttpModule, который обрабатывает изображения с использованием асинхронного программирования.Правильное использование ConcurrentQueue в HttpModule?
Несмотря на то, что я уверен, что получаю повышение производительности, я хотел бы проверить, что я правильно использую инструменты.
Я особенно обеспокоен тем, что обрабатываю очередь неправильно.
Подход, который я принимаю.
- инициализировать ConcurrentQueue
- Добавить метод ProcessImage в очереди на в BeginEventHandler в AddOnBeginRequestAsync
- процесса Очередь на EndEventHandler в AddOnBeginRequestAsync
Там много кода, так что мои извините заранее, но асинхронное программирование сложно:
поля
/// <summary>
/// The thread safe fifo queue.
/// </summary>
private static ConcurrentQueue<Action> imageOperations;
/// <summary>
/// A value indicating whether the application has started.
/// </summary>
private static bool hasAppStarted = false;
HttpModule INIT
/// <summary>
/// Initializes a module and prepares it to handle requests.
/// </summary>
/// <param name="context">
/// An <see cref="T:System.Web.HttpApplication"/> that provides
/// access to the methods, properties, and events common to all
/// application objects within an ASP.NET application
/// </param>
public void Init(HttpApplication context)
{
if (!hasAppStarted)
{
lock (SyncRoot)
{
if (!hasAppStarted)
{
imageOperations = new ConcurrentQueue<Action>();
DiskCache.CreateCacheDirectories();
hasAppStarted = true;
}
}
}
context.AddOnBeginRequestAsync(OnBeginAsync, OnEndAsync);
context.PreSendRequestHeaders += this.ContextPreSendRequestHeaders;
}
обработчики событий
/// <summary>
/// The <see cref="T:System.Web.BeginEventHandler"/> that starts
/// asynchronous processing
/// of the <see cref="T:System.Web.HttpApplication.BeginRequest"/>.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">
/// An <see cref="T:System.EventArgs">EventArgs</see> that contains
/// the event data.
/// </param>
/// <param name="cb">
/// The delegate to call when the asynchronous method call is complete.
/// If cb is null, the delegate is not called.
/// </param>
/// <param name="extraData">
/// Any additional data needed to process the request.
/// </param>
/// <returns></returns>
IAsyncResult OnBeginAsync(
object sender, EventArgs e, AsyncCallback cb, object extraData)
{
HttpContext context = ((HttpApplication)sender).Context;
EnqueueDelegate enqueueDelegate = new EnqueueDelegate(Enqueue);
return enqueueDelegate.BeginInvoke(context, cb, extraData);
}
/// <summary>
/// The method that handles asynchronous events such as application events.
/// </summary>
/// <param name="result">
/// The <see cref="T:System.IAsyncResult"/> that is the result of the
/// <see cref="T:System.Web.BeginEventHandler"/> operation.
/// </param>
public void OnEndAsync(IAsyncResult result)
{
// An action to consume the ConcurrentQueue.
Action action =() =>
{
Action op;
while (imageOperations.TryDequeue(out op))
{
op();
}
};
// Start 4 concurrent consuming actions.
Parallel.Invoke(action, action, action, action);
}
делегатом и р rocess
/// <summary>
/// The delegate void representing the Enqueue method.
/// </summary>
/// <param name="context">
/// the <see cref="T:System.Web.HttpContext">HttpContext</see> object that
/// provides references to the intrinsic server objects
/// </param>
private delegate void EnqueueDelegate(HttpContext context);
/// <summary>
/// Adds the method to the queue.
/// </summary>
/// <param name="context">
/// the <see cref="T:System.Web.HttpContext">HttpContext</see> object that
/// provides references to the intrinsic server objects
/// </param>
private void Enqueue(HttpContext context)
{
imageOperations.Enqueue(() => ProcessImage(context));
}
Спасибо за это, да, я обязательно изменю имя поля. :) Вы очень сильно подхватили то, что меня беспокоило в «OnEndAsync». Я получил 4 потока бит из образца в MSDN, и я не был уверен, что это было либо выгодно, либо вредно для моего процесса. Сказав это, сокращение процесса до одного потока, похоже, ускорило мою тестовую страницу на ~ 20%. Будет ли иметь смысл сохранить только один или вы могли бы предложить способ, которым больше потоков можно было бы использовать более выгодным образом? –
Спасибо за это ... К сожалению, ваше редактирование что-то сломало. Изображения, безусловно, обрабатываются и сохраняются в файловой системе, но теперь они возвращаются в браузер в необработанной необработанной форме. –
Да, это имеет смысл. Вернемся к чертежной доске, если мне нужна дополнительная скорость:/ –