gpt4 book ai didi

C#并行IO完成端口

转载 作者:行者123 更新时间:2023-11-30 12:33:46 25 4
gpt4 key购买 nike

我正在尝试找出等待一定数量的 I/O 完成端口完成的最佳方法。

对于这种情况,假设我在 MVC3 网络应用程序中。 (我的理解是这里建议使用 I/O 完成端口,这样我可以将原始线程返回到 IIS 以服务其他请求)

假设我有一个 ID 数组,我想从某个网络调用中为每个 ID 获取一个对象。

并行化这种同步方法的最佳方式是什么?

   public class MyController: Controller
{
public ActionResult Index(IEnumerable<int> ids)
{
ids.Select(id => _context.CreateQuery<Order>("Orders")
.First(o => o.id == id));
DataServiceQuery<Order> query = _context.CreateQuery<Order>("Orders");
return Json(query);
}

private DataServiceContext _context; //let's ignore how this would be populated
}

我知道它会这样开始:

   public class MyController: AsyncController
{
public void IndexAsync(IEnumerable<int> ids)
{
// magic here...

AsyncManager.Sync(() => AsyncManager.Parameters["orders"] = orders);
}

public ActionResult IndexCompleted(IEnumerable<Order> orders)
{
return Json(orders);
}

private DataServiceContext _context; //let's ignore how this would be populated
}

我应该使用 DataServiceContext.BeginExecute 吗?方法? DataServiceContext.BeginExecuteBatch ?我使用的数据服务一次只能获取一条记录(这是我无法控制的),我希望这些单独的查询并行运行。

最佳答案

这是我最终用于在 MVC3 中运行一批异步操作的模式:

public class MyController: AsyncController
{
public void IndexAsync(int[] ids)
{
var orders = new Orders[ids.Length];
AsyncManager.Parameters["orders"] = orders;

// tell the async manager there are X operations it needs to wait for
AsyncManager.OutstandingOperations.Increment(ids.Length);

for (int i = 0; i < ids.Length; i++){
var index = i; //<-- make sure we capture the value of i for the closure

// create the query
var query = _context.CreateQuery<Order>("Orders");

// run the operation async, supplying a completion routine
query.BeginExecute(ar => {
try {
orders[index] = query.EndExecute(ar).First(o => o.id == ids[index]);
}
catch (Exception ex){
// make sure we send the exception to the controller (in case we want to handle it)
AsyncManager.Sync(() => AsyncManager.Parameters["exception"] = ex);
}
// one more query has completed
AsyncManager.OutstandingOperations.Decrement();
}, null);
}
}

public ActionResult IndexCompleted(Order[] orders, Exception exception)
{
if (exception != null){
throw exception; // or whatever else you might like to do (log, etc)
}
return Json(orders);
}

private DataServiceContext _context; //let's ignore how this would be populated
}

关于C#并行IO完成端口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8526721/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com