激活线程 C#
我在 C# 中有这段代码:
Thread t1 = new Thread(functionsActivations(3, 4000, 0, 4));
Thread t2 = new Thread(functionsActivations(3, 4000, 5, 9));
t1.start();
t2.Start();
Thread t3 = new Thread(functionsActivations(4, 4000, 0, 4));
Thread t4 = new Thread(functionsActivations(4, 4000, 5, 9));
它不起作用。我怎样才能告诉它调用我给它的方法? 其次,我希望在 t1 和 t2 完成运行后激活 t3 和 t4。我怎样才能做到这一点? 第三,我希望 t1 和 t2 不阻塞(这样 t2 就不必等到 t1 完成)。我的做法正确吗?
i have this code in C#:
Thread t1 = new Thread(functionsActivations(3, 4000, 0, 4));
Thread t2 = new Thread(functionsActivations(3, 4000, 5, 9));
t1.start();
t2.Start();
Thread t3 = new Thread(functionsActivations(4, 4000, 0, 4));
Thread t4 = new Thread(functionsActivations(4, 4000, 5, 9));
It is not working. How can I tell it to call the method I gave it?
Secondly, I want t3 and t4 to be activated after t1 and t2 finish running. How can I do that?
Third, I want t1 and t2 to not block (so that t2 wouldn't have to wait until t1 finishes). Is what I did correct?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
“它不起作用”并不是一组非常明确的症状。你在观察什么?
编辑:好的,现在您已经说了编译器错误是什么,诊断起来就容易多了。您当前正在调用一个方法并尝试将结果用作线程执行的任务。假设您实际上想要在线程启动时调用该方法,您需要如下所示的内容:
C# 2:
C# 3:
到处使用 lambda 表达式的替代方法是编写一个实用程序方法:
然后你可以使用:
等等。
对于本文的其余部分,我将假设使用 C# 3。
此外,
t1.start()
应该是t1.Start()
- C# 区分大小写。为了回答你的最后一点,
t1
和t2
目前是独立的 - 它们不会互相阻塞,除非你在它们运行的代码中的某个地方进行了同步。如果您只想在
t1
和t2
完成时启动t3
和t4
,则可以使用Thread.Join
:请注意,这意味着这个线程也将等待
t1
和t2
完成。如果这对您来说还不够好,有多种选择,但基本上您会想要其他东西来异步等待 t1 和 t2 完成。例如,您可以绑定一个额外的线程来执行此操作:有点令人讨厌,但它应该可以工作。
你能使用.NET 4.0吗?如果是这样,并行扩展框架会使这一切变得更加容易。
"It is not working" isn't a very clear set of symptoms. What are you observing?
EDIT: Okay, now that you've said what the compiler error is, it's much easier to diagnose. You're currently calling a method and trying to use the result as a task for the thread to execute. Assuming you actually want to make that method call when the thread is started, you want something like this:
C# 2:
C# 3:
An altnerative to having lambda expressions all over the place would be to write a utility method:
Then you could use:
etc.
For the rest of the post I'll assume C# 3.
Additionally,
t1.start()
should bet1.Start()
- C# is case sensitive.To answer your final point,
t1
andt2
are currently independent - they won't be blocking each other unless you've got synchronization somewhere in the code that they're running.If you only want
t3
andt4
to start whent1
andt2
have finished, you could useThread.Join
:Note that that means that this thread will wait until
t1
andt2
have finished, too. If that's not good enough for you, there are various options but basically you'll want something else to asynchronously wait for t1 and t2 to complete. For example, you could tie up an extra thread to do that:Somewhat icky, but it should work.
Are you able to use .NET 4.0? If so, the Parallel Extensions framework makes a lot of this significantly easier.