【发布时间】:2016-08-14 05:06:34
【问题描述】:
我需要为不同的列表参数运行相同的方法。例如 List X , List Y 等,当方法启动时,它永远不会停止,直到用户关闭应用程序,如下所示。我的问题是,在运行时,如果我有列表 X,Foo 方法必须作为不同的任务工作,顺便说一下,新项目可以在运行时添加到列表中,如果新参数添加到列表 X,当方法工作时,我确保 X 的新项目进入相同的方法任务。如何使用 task.CurrentId 处理这个问题?是否可以获取任务 currentId 并将参数发送到该特定任务?
public void Foo(string name)
{
while(true)
{
//some process
}
}
GetNewParameter(String sample)
{
if(someCase)
{
//if there is a foo method runing on X list on a different Task, I must add
//and make sure to be new parameter is sent to Foo method working on already X
//List.
X.Add(sample);
//Task.Factory.StartNew(() => foo(sample));
//Send to already running task
}
if(someCase)
{
//If there is no task working on Y list I need to create a new task to run Foo
//method on it.
Y.Add(sample);
Task.Factory.StartNew(() => foo(sample));
}
}
【问题讨论】:
-
使用一些你将要填充的集合,“任务”将被消耗。生产者-消费者模式。为什么使用相同的任务对您来说如此重要?以及你想如何实际使用它?
-
Lists 有不同类型的字符串,并且每个列表的项目相互关联,所以如果有一个方法在 X 列表上工作,新项目将添加到 X 列表中,我无法创建新任务,它必须在已经在 X 列表项上工作的相同任务中进行评估。
-
好的,但是想象一下你有你想要的任务......你想如何使用它......一旦你创建了它,你就无法访问它正在运行的动作......跨度>
-
嗯。我明白了,我明白了,你的意思是我不能向 runnnig 方法发送任何参数,但是是否可以在方法中保留一个列表,例如 Foo 中的列表 X,我尝试将新项目添加到列表中以进行评估?但当然同样的事情发生在这里,我确保在 runnung x list 上工作方法
-
请务必正确锁定资源... System.Collections.Concurrent 命名空间有一些非常有用的集合。
标签: c# asynchronous task-parallel-library task