我需要做一些上传后处理。
用户上传包含大量图像的.zip (通常在100到500之间)。我需要处理这个压缩文件来提取、修改和存储图像。
我的问题是,这个后处理有点长,所以用户会得到一个HTTP错误500,因为分配给处理请求的时间已经结束。
实际过程:
我希望有一个异步的后处理:
有可能吗?有更好的方法吗?
注:没有代码,因为这只是一个关于建筑的问题
发布于 2016-01-13 11:30:16
只需在另一个线程中执行您的后处理。
你可以用
Task.Factory.StartNew(() =>
{
/*your post-processing code*/
//...etc
/*when finished, notify user that post-processing has finished, maybe by email*/
});最好不要让所有请求都创建新线程。对于很多并发用户来说,这将是非常糟糕的。而是创建一个"worker“线程,逐个执行”排队任务“。
所以你可以:
private class ProcessItem
{
//define each task data
}
private static readonly ConcurrentQueue<ProcessItem> queue
= new ConcurrentQueue<ProcessItem>();
private static Thread worker = new Thread(() =>
{
while (true) // infinite
{
ProcessItem item;
if (!queue.TryDequeue(out item))
{ //no availble items, wait for an item
Monitor.Enter(queue); Monitor.Wait(queue); Monitor.Exit(queue);
continue; //I have been notified, repeat check
}
//now process item
}
});
static YourClass()
{
worker.Start(); //start the worker at class first-load
}若要将项添加到队列中,请执行以下操作:
queue.Enqueue(item);
Monitor.Enter(queue);
Monitor.PulseAll(queue); //notifiy the waiting threads
Monitor.Exit(queue);https://stackoverflow.com/questions/34765487
复制相似问题