并行循环调用API
我正在使用并行循环将数据从 C# 发布到 API,列表中有 1000 多个对象。响应仅是成功或失败。我需要使用适当的 ID 在日志文件中记录失败的记录。当我将对象发送到 API 时,我将 ID 保留在循环内的局部变量中并发布数据。当响应返回时,我假设我收到的该 ID 的响应并写入日志。
ParallelOptions po = new ParallelOptions
{
MaxDegreeOfParallelism = 2
};
Parallel.ForEach(lstPost, po, obj=>
{
string id= obj.Id;
var response= API calls goes here......;
if(response.Status== "ERROR")
{
//log the details
Log.Write(ID : response.Status)
}
}
我的疑问是,有没有机会得到别人对别人id的回复?
I am using a parallel loop for posting data to API from C#, having 1000+ objects in the list. The response is either success or failure only. I need to log failed record in the log file with appropriate ID. When I am sending the object to API, I keep the ID in local variable inside the loop and posting the data. When the response comes back, I am assuming that the response what I am getting for that ID and writing the log.
ParallelOptions po = new ParallelOptions
{
MaxDegreeOfParallelism = 2
};
Parallel.ForEach(lstPost, po, obj=>
{
string id= obj.Id;
var response= API calls goes here......;
if(response.Status== "ERROR")
{
//log the details
Log.Write(ID : response.Status)
}
}
My doubt is, there is any chance to get someone else's response to someone else's id?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只有 API 调用是线程安全的,它才是安全的。这是一个相当安全的假设,但我总是建议在假设任何有关线程安全的事情之前先检查文档。
循环体内的 id 和 response 是局部变量,因此不会在任何线程之间共享,因此非常安全。一般来说,线程安全的问题是共享可变状态,如果状态是非共享或不可变的,那么它是完全安全的。
您还应该考虑日志记录功能的线程安全性。大多数日志库提供线程安全的日志记录功能,但请再次检查文档以确保安全。为了安全起见,直接写入文件可能需要一些同步(例如锁)。
然而,这样的并行循环将启动两个线程,每个线程都进行 API 调用。大多数情况下,进行 API 调用可能只是在等待结果,在此期间线程将被阻塞,这有点浪费。使用
Parallel.ForEachAsync
或Task.WhenAll
可以允许异步进行 API 调用,因此在等待响应时根本不使用任何线程,从而节省一些资源。It would be safe only if the API calls are thread safe. It would be a fairly safe assumption that they are, but I would always recommend checking the documentation before assuming anything in regards to thread safety.
The id and response inside the loop body are local variables, and thus not shared between any threads, and therefore perfectly safe. In general, the problem with thread safety is shared mutable state, if state is either non-shared or immutable it is perfectly safe.
You should also consider the thread safety of the logging function. Most log-libraries provide thread safe logging functions, but again, check the documentation to be safe. Directly writing to a file would likely require some synchronization, like a lock, to be safe.
However such a parallel loop will start two threads where each make a API-call. Most of the time making an API call will probably just be waiting for the result, and during this time the threads will just block, and this is a bit wasteful. Using
Parallel.ForEachAsync
orTask.WhenAll
could allow your API calls to be made asynchronously, and therefore not use any thread at all while waiting for the response, saving some resources.