简体   繁体   English

循环内的回调(异步方法调用)

[英]Callbacks (Asynchronous Method Calls) within a Loop

Part of a C# application I'm writing requires collecting data from a service provider's database for each account associated to a user. 我正在编写的C#应用​​程序的一部分要求从服务提供商的数据库中为与用户相关联的每个帐户收集数据。 When the user logs into the app a call is made to start updating the accounts from the service provider's database. 当用户登录到应用程序时,将进行调用以开始从服务提供商的数据库中更新帐户。 Since lots operations are performed on the third party's end the process of getting their information could take a while so I don't want to wait for each account just to start the process of updating. 由于大量操作是在第三方端执行的,因此获取他们的信息的过程可能会花费一些时间,因此我不想等待每个帐户都只是开始更新过程。 My question is, is there any issues (maybe threading issues) with calling a asynchronous method inside of a loop? 我的问题是,在循环内调用异步方法是否有任何问题(可能是线程问题)?

The only loop-specific issue is that if you use anonymous methods that refer to loop variables, each time around the loop an instance of the anonymous method object will be created but they will all refer to the same loop variable, so they will see it change its value as the loop executes. 唯一的特定于循环的问题是,如果您使用引用循环变量的匿名方法,则每次循环时都会创建一个匿名方法对象的实例,但是它们都将引用相同的循环变量,因此他们将看到它在循环执行时更改其值。 So make a copy of the loop variable inside the loop. 因此,请在循环内复制循环变量。

foreach (var thing in collection)
{
    var copy = thing;

    Action a = () =>
               {
                   // refer to copy, not thing
               }
}

2017-04-25: By the way, this issue was solved by C# 5.0. 2017-04-25:顺便说一句,此问题已由C#5.0解决。 foreach automatically performs the above transformation. foreach自动执行上述转换。

The loop is no problem, but starting (too) many threads might be. 循环没问题,但是可能启动了太多线程。 See if your requirements allow using a the ThreadPool . 查看您的要求是否允许使用ThreadPool

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM