gpt4 book ai didi

c# 阻塞收集和线程

转载 作者:行者123 更新时间:2023-11-30 23:19:22 25 4
gpt4 key购买 nike

我刚开始使用阻塞收集和线程,想确保自己遵循了最佳实践。我正在使用非线程安全的第三方 API。我将同时向 API 发出多个请求,因此我需要将这些请求添加到队列中并一个接一个地处理它们。为此,我有一个阻塞集合:

    BlockingCollection<myEventArgs> myTasks = new BlockingCollection<myEventArgs>();

private void myEventHandler(object sender, myEventArgs e)
{
myTasks.Add(e);
}

private void doWork()
{

while (myTasks.IsCompleted == false)
{

//Do some work here with the third party API.
var eArgs = myTasks.Take();

//Sometimes I have a background (thread safe) task to perform.
//This is submitted to the thread pool.
Task.Run(() => doSomeBackgroundWork());

}
}

有时我会有一个线程安全的后台任务要执行。例如,API 调用是异步的,我需要轮询第三方系统以检查任务是否完成。我不希望这会阻止 BlockingCollection 处理下一个任务,所以我将其提交给线程池。一旦线程池任务完成,它将触发一个事件,该事件将一个新任务添加到 BlockingCollection。

此解决方案是否合适?是否有任何可能出错的地方?我假设处理 BlockingCollection 中的项目的 doWork 方法将始终在同一线程中运行是否正确?当我从线程池触发事件时,只有事件会在线程池上运行,而不是后续的 doWork 方法?

最佳答案

Is this solution appropriate

基本上,是的。这是生产者/消费者的情况,而这正是 BlockingCollection 的用途。

is there anything that could go wrong with this?

您必须非常确定 doSomeBackgroundWork() 对于您的 doWork() 代码是线程安全的。

根据可以推送多少 myEventArgs,为您的阻塞集合设置上限可能是个好主意。

关于c# 阻塞收集和线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40339390/

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