在没有等待的情况下异步调用方法,返回类型是无效的 [英] Call Method Asynchronously without await and which are return type are non void

查看:75
本文介绍了在没有等待的情况下异步调用方法,返回类型是无效的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hello All,


在我当前的应用程序中,我想同时调用方法,但每个方法都返回字典对象。这就是我需要在它们之前使用await关键字的原因。如果等待是使用它们,它们会被连续排除。 


有没有办法在没有await关键字的情况下同时调用它们,这样最大的排除时间将是方法所需的最长时间在他们之外?


先谢谢。


-


问候,


Atul Gaikwad。


解决方案

这就是我的工作方式:

 List< Task< Dictionary< string,string>>> tasks = new List< Task< Dictionary< string,string>>>(); 
for(int i = 0; i< 10; ++ i)
{
tasks.Add(TaskAsync());
}

for(int i = 0; i< 10; i ++)
{
// do stuff
Dictionary< string,string> result =等待任务[i];
}

首先,只需调用它们并将它们存储到数组或列表中即可启动它们。

比你串行处理它们的结果。


它们将在不同时间完成,并且可以在完成后单独处理每个,但如果您只需要同时运行它们,这就足够了。 


您也可以使用.ContinueWith,在完成后立即处理:

 TaskAsync()。ContinueWith(
async s =>
{
// Do stuff
Dictionary< string,string> result = await s;
});

你可以混合两个approuches。


注意:还有其他解决这个问题的方法,但我需要确切知道你希望它如何工作。


Hello All,

In my current application,  I want to call method simultaneously but each of them return dictionary object. that's why i need to use await keyword before them. and if await is use them they are exicuted serially. 

Is there any way to call them simultaneously without await keyword , so that maximum exicution time will be the highest time taken by method out of them ?

Thanks in advanced.

--

Regards,

Atul Gaikwad.

解决方案

This is how I do it:

            List<Task<Dictionary<string, string>>> tasks = new List<Task<Dictionary<string, string>>>();
            for (int i = 0; i < 10; ++i)
            {
                tasks.Add(TaskAsync());
            }

            for (int i = 0; i < 10; i++)
            {
                // Do stuff
                Dictionary<string, string> result = await tasks[i];
            }

First you start them all by simply calling them and storing them into array or list.
Than you process their result serially.

They will finish in different time and it possible to process each individually after it completes but if you need only to run them all at same time, this is good enough. 

You can also use .ContinueWith, process stuff right after they are finished:

TaskAsync().ContinueWith(
                    async s =>
                        {
                            // Do stuff
                            Dictionary<string, string> result = await s;
                        });

You can mix and both approuches.

Note: There are also other approaches to this problem but I'll need to know exactly how you want this to work.


这篇关于在没有等待的情况下异步调用方法,返回类型是无效的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆