我正在使用以下方法创建许多线程
Task.Factory.StartNew(() =>
{
//do some task here
});
在某些时候我想执行一个方法,但在此之前我想
任何好的解决方案都将受到赞赏。
提前致谢
--------------------已编辑的代码-----------------------
for (int i = 0; i < 10; i++)
{
Task.Factory.StartNew(() =>
{
Console.WriteLine("First Thread @ " + DateTime.Now.ToString());
});
}
当我们达到此调用时,应该在执行
之前检查所有待处理的任务Console.WriteLine(“*******************称为另一种方法******************** ***“);
当执行上述操作并且另一个请求与下面相同时,它应该只在执行上面的行(在我的情况下方法中)之后开始。
for (int i = 0; i < 10; i++)
{
Task.Factory.StartNew(() =>
{
Console.WriteLine("Second Thread @ " + DateTime.Now.ToString());
});
}
答案 0 :(得分:0)
我认为你真正想要的是实现某种在单个线程中执行工作的Queue。这是一些最小的实现(未经测试!)
class QueuedWorker
{
ConcurrentQueue<Action> queue = new ConcurrentQueue<Action>();
ManualResetEvent waiter = new ManualResetEvent(false);
Thread workerThread;
public QueuedWorker()
{
workerThread = new Thread(ThreadWorker);
workerThread.Start();
}
private void ThreadWorker()
{
Action nextTask;
while(true)
{
while(queue.TryDequeue(out nextTask))
{
// run the queued task
nextTask();
}
waiter.WaitOne();
waiter.Reset();
}
}
public void Enqueue(Action item)
{
queue.Enqueue(item);
waiter.Set();
}
}
答案 1 :(得分:0)
我通过将创建的任务存储到列表中并对其应用锁定来解决我自己的问题。
class Program
{
static List<Task> taskList = new List<Task>();
static void Main(string[] args)
{
Task.Factory.StartNew(() => { StartTasks("First"); });
Task.Factory.StartNew(() => { LoadMethod(); });
Task.Factory.StartNew(() => { StartTasks("Second"); StartTasks("Third"); });
Task.Factory.StartNew(() => { LoadMethod(); });
Task.Factory.StartNew(() => { StartTasks("Four"); });
Task.Factory.StartNew(() => { LoadMethod(); });
Task.Factory.StartNew(() => { StartTasks("Five"); StartTasks("Six"); StartTasks("Seven"); StartTasks("Eight"); });
Task.Factory.StartNew(() => { LoadMethod(); });
Task.Factory.StartNew(() => { StartTasks("Nine"); StartTasks("Ten"); });
Task.Factory.StartNew(() => { LoadMethod(); });
Console.WriteLine("Execution is completed !");
Console.ReadKey();
}
public static void LoadMethod()
{
// Lock and wait to not allow any thead to modify the list
lock (taskList)
{
if (taskList.Any())
{
Task.WaitAll(taskList.ToArray());
}
Debug.WriteLine("*******************Called Another Method***********************");
taskList.Clear();
}
}
public static void StartTasks(string taskName)
{
lock (taskList)
{
for (int i = 0; i < 10; i++)
{
var t = new Task(() =>
{
Debug.WriteLine(taskName + " @ " + DateTime.Now.ToString());
//System.Threading.Thread.Sleep(500);
});
taskList.Add(t);
}
Task.Factory.StartNew(() => taskList.ForEach(task =>
{
if (task.Status == TaskStatus.Created)
{
task.Start();
}
}), TaskCreationOptions.AttachedToParent);
}
}
}