2012-10-31 28 views
1

我有一個簡單的應用程序,處理從窗體提交的文件。我試圖用下面列出的代碼異步運行文件處理。如何在ServiceStack的onPost方法中啓動異步處理?

不幸的是,在長時間運行StaticProcessingMethod完成後,http響應被返回。

在提交時異步處理文件的正確方法是什麼?

public override object OnPost(Item item) 
{ 
    System.ComponentModel.BackgroundWorker worker = new System.ComponentModel.BackgroundWorker(); 
    worker.DoWork += new System.ComponentModel.DoWorkEventHandler(
     delegate(object o, System.ComponentModel.DoWorkEventArgs args) 
     { 
      StaticProcessingMethod(base.RequestContext.Files[0].InputStream); 
     }); 

    worker.RunWorkerAsync(); 

    return new HttpResult("Processing started", ContentType.PlainText + ContentType.Utf8Suffix); 
} 

回答

1

我會將一個後臺線程打包並注入爲一個依賴項,它只是將它需要處理的任務列表排隊。例如例如:

public IBackgroundProcessor BackgroundProcessor { get; set; } 

public object Post(Item item) 
{ 
    BackgroundProcessor.Enqueue(
     new StaticProcessingTask(item, base.RequestContext.Files[0].InputStream)); 

    return new HttpResult("Processing started", 
     ContentType.PlainText + ContentType.Utf8Suffix); 
} 

後臺線程在AppHost中啓動。排隊任務會將其排入併發隊列並通知/喚醒後臺睡眠線程,否則,如果bg線程仍在運行,則會在處理所有待處理任務後進入睡眠狀態。

注意:上面的示例代碼使用ServiceStack's improved New API