ASP.NET маршрутизация MVC и области

Я предполагаю, что некоторое событие в GUI требует некоторой продолжительной задачи запуститься, которые выполняются в фоновом режиме - существует два основных способа сделать это. Если Вы просто хотите назвать метод на различном потоке тогда, можно сделать это Звонящие Синхронные Методы Асинхронно . Я обычно делаю что-то вроде этого:



//delegate with same prototype as the method to call asynchrously
delegate void ProcessItemDelegate(object item);

//method to call asynchronously
private void ProcessItem(object item) { ... }

//method in the GUI thread
private void DoWork(object itemToProcess)
{
    //create delegate to call asynchronously...
    ProcessItemDelegate d = new ProcessItemDelegate(this.ProcessItem);
    IAsyncResult result = d.BeginInvoke(itemToProcess,
                                        new AsyncCallback(this.CallBackMethod),
                                        d); 
}

//method called when the async operation has completed
private void CallbackMethod(IAsyncResult ar)
{
    ProcessItemDelegate d = (ProcessItemDelegate)ar.AsyncState;
    //EndInvoke must be called on any delegate called asynchronously!
    d.EndInvoke(ar);
}

знать при использовании этого метода, что обратный вызов выполняется на фоновом потоке, таким образом, любые обновления GUI должны быть сделаны с помощью, Вызывают.

, Кроме того, Вы могли использовать общее состояние, чтобы связаться между потоками и использовать EventWaitHandle для передачи сигналов об обновлениях общего состояния - в этом примере, метод в GUI добавляет объекты работы к очереди, чтобы быть обработанным в фоновом режиме. Рабочий поток обрабатывает объекты от очереди, когда работа становится доступной.


//shared state
private Queue workQueue;
private EventWaitHandle eventHandle;

//method running in gui thread
private void DoWork(Item itemToProcess)
{
   //use a private lock object instead of lock...
   lock(this.workQueue)
   {
       this.workQueue.Add(itemToProcess);
       this.eventHandle.Set();
   }
}

//method that runs on the background thread
private void QueueMonitor()
{
   while(keepRunning)
   {
       //if the event handle is not signalled the processing thread will sleep here until it is signalled or the timeout expires
       if(this.eventHandle.WaitOne(optionalTimeout))
       {
           lock(this.workQueue)
           {
              while(this.workQueue.Count > 0)
              {
                 Item itemToProcess = this.workQueue.Dequeue();
                 //do something with item...
              }
           }
           //reset wait handle - note that AutoResetEvent resets automatically
           this.eventHandle.Reset();
       }
   }
}

13
задан Dan Appleyard 25 October 2009 в 19:16
поделиться

2 ответа

Зарегистрируйте области в одном проекте

Вам необходимо добавить файл routes.cs в папку админки.

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcAreasSingleProject.Areas.Admin
{
    public class Routes : AreaRegistration
    {
        public override string AreaName
        {
            get { return "admin"; }
        }

        public override void RegisterArea(AreaRegistrationContext context)
        {
            context.MapRoute(
                "admin_default",
                "admin/{controller}/{action}/{id}",
                new { controller = "Admin", action = "Edit", id = "" }
            );
        }
    }
}
27
ответ дан 1 December 2019 в 21:12
поделиться

http://haacked.com/archive/2009/07/31/single-project-areas.aspx

routes.MapAreaRoute("Forums", 
        "admin_area", 
        "admin/{controller}/{action}/{id}", 
        new { controller = "apples", action = "search", id = "" }, 
        new string[] { "Project.Areas.Admin.Controllers" });
0
ответ дан 1 December 2019 в 21:12
поделиться
Другие вопросы по тегам:

Похожие вопросы: