C#中的一个新的线程调用的方法 [英] C# Call a method in a new thread

查看:157
本文介绍了C#中的一个新的线程调用的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要寻找一种方式来调用一个新的线程的方法(使用C#)。
比如说,我想打电话给 SecondFoo()上一个新的线程。不过,我会那么喜欢当 SecondFoo()结束已经线程终止。

I am looking for a way to call a method on a new thread (using C#). for instance, I would like to call SecondFoo() on a new thread. However, I would then like to have the thread terminated when SecondFoo() finishes.

我见过几个例子在 C#线程,但没有适用于该特定方案;我需要在衍生线程终止本身。这可能吗?

I have seen several examples of threading in C#, but none that apply to this specific scenario; where I need the spawned thread to terminate itself. Is this possible?

如何可以强制运行在衍生线程 Secondfoo()完成后终止?

How can I force the spawned thread running Secondfoo() to terminate upon completion?

已经走过了任何的例子有人进来???

Has anyone come across any examples of this???

非常感谢,
布雷特

Many thanks, Brett

推荐答案

如果你真正开始一个新的线程,该线程的将会的终止时方法完成:

If you actually start a new thread, that thread will terminate when the method finishes:

Thread thread = new Thread(SecondFoo);
thread.Start();

现在 SecondFoo 将在新的名为线程,该线程将它完成时终止。

Now SecondFoo will be called in the new thread, and the thread will terminate when it completes.

你的真正的意思是你想要的线程终止时,在该方法呼叫的线程完成

Did you actually mean that you wanted the thread to terminate when the method in the calling thread completes?

编辑:?请注意,启动一个线程是一个相当昂贵的操作。你肯定需要一个品牌的新的的线程,而不是使用线程池线程?请考虑使用 ThreadPool.QueueUserWorkItem 或(最好,如果你使用.NET 4)的 TaskFactory.StartNew

Note that starting a thread is a reasonably expensive operation. Do you definitely need a brand new thread rather than using a threadpool thread? Consider using ThreadPool.QueueUserWorkItem or (preferrably, if you're using .NET 4) TaskFactory.StartNew.

这篇关于C#中的一个新的线程调用的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆