我想使用异步调用并行运行多个事务,但是在任何事务中我都想按顺序处理所有任务,因为顺序很重要。我使用异步调用,但无济于事,它使整个事务异步,从而产生冲突。
假设我要并行处理多个公司的数据,但是要依次处理公司的数据,我需要产品的productid来获取产品的详细信息,因此首先我必须获取所有产品,然后使用针对公司的productid来获取产品的详细信息。没有productid我无法获得产品详细信息。
Task WrappedInTask = Task.Run(() => CompanyAsync(companyId));
public static async Task CompanyAsync(int companyId)
{
string[] products=getAllProducts(compnyId);
for(int i=0; i<products.length>i; i++)
{
//get product detail here using products[i]
}
}
我想完全执行getAllProducts(compnyId),然后执行for循环,如果for循环和getAllProducts(compnyId)方法将异步地退出,那么将发生冲突。任何建议做到这一点
如果getAllproducts(compnyId)
也是异步方法,那么您可以在执行for循环之前简单地等待它完成:
string[] products = await getAllProducts(compnyId);
for(int i = 0; i < products.length; i++)
{
// ...
}
无论如何,我不知道您当前的代码示例如何进行编译。如果getallProducts
实际上是一个async
方法,则string[] products = getAllProducts(compnyId)
应该抛出一个错误,因为它返回aTask<string[]>
而不是a string[]
。
编辑
您不应将并行性与异步性混淆。
似乎您想并行地对列表进行迭代。
async
如果您要执行固有的异步操作(例如I / O),通常会使用这些方法,否则就不需要它们。
您可以将System.Threading.Tasks.Parallel类用于您的任务。
//This will probably create new threads (or not) and will iterate your list concurrently
Parallel.ForEach(dt.Rows, dataRow =>
{
int companyId = //Fetch companyId
Company(companyId);
});
//Code here will execute after each element has been paralelly iterated.
请注意,您的新CompanyAsync
方法签名应更改为:
public static void Company(int companyId);
有关如何使用此方法的更多参考,请阅读:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句