每次调用特定方法时创建一个新的后台线程
WinForm: 我的 MainApplication 中有一个名为 check_news 的方法。 如何创建并运行一个线程,每次调用该方法时(通过按按钮或在程序启动时),该线程都会在后台处理该方法?
我知道如何创建一个线程,但是每次调用该函数时如何创建新线程(新线程因为旧线程已死)?
我应该创建一个新类并使用新类对象和我需要的方法运行线程吗? 我应该在哪里定义线程?
WinForm:
I have a method called check_news in my MainApplication.
How can I create and run a Thread that will work on the method on background each time I call the method (by pushing a button, or in the start of the program)?
I know how to create a thread but how can I create new thread every time I call the function (new thread because the old one is dead)?
Should I create a new class and run the thread with the new class object and the method I need?
Where should I define the thread?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以通过编写
new Thread(...)
在方法内创建一个线程。...
可以是方法名称、委托实例或匿名方法。每次执行此代码时,都会创建一个新的 Thread 实例。
请注意,使用
ThreadPool
会更高效。You can just create a thread inside the method by writing
new Thread(...)
.The
...
can be a method name, delegate instance, or anonymous method.Each time this code executes, it will create a new
Thread
instance.Note that it will be more efficient to use the
ThreadPool
instead.我认为实现这一点的最佳方法是将其添加到线程池中,它既简单又快速。
示例:
或者,如果您确实想自己处理它,则可以使用以下内容:
但您应该知道,这需要更长的时间来启动,它不会重用线程,并且没有真正的优势。
或者,如果您想要更多控制,可以使用异步平台:
请注意,所有示例中的 lambda 表达式也可以替换为常规函数。但我现在就使用它们,因为作为例子看起来更好。
I suppose the best way to achieve this is by adding it to the thread pool, it's easy and quick.
Example:
Or if you really want to deal with it yourself, this is something you could use:
But you should know that this takes a longer time to start, it doesn't reuse threads, and there's not a real advantage in it.
Or if you want more control you could use the async platform:
Note that the lambda expressions in all examples can just as well be replaced by regular functions. But I just use them right now, because it seems nicer as example.