创建线程(Background Thread)的N种方式

本文详细介绍了C#中创建线程的多种方法,包括Thread类、ThreadPool、delegate委托、BackgroundWorker、Timer、Task类、Task.Factory、Parallel类及Observable类,并提供了实践示例。

原文地址:http://www.cnblogs.com/xchit/p/3425542.html

第一、Thread类

  Thread类是实例化线程的主要方法;一个Thread实例管理一个线程,即执行序列。通过简单实例化一个对象,就可以创建一个线程,然后通过Thread对象提供的方法对线程进行管理。

  

Thread thread = new Thread(_ => BackgroundMethod("第一、Thread类创建线程"));
            thread.Start();
            thread.Join();

 

第二、ThreadPool(线程池)类

  提供一个线程池,该线程池可用于执行任务、发送工作项、处理异步 I/O、代表其他线程等待以及处理计时器。

ThreadPool.QueueUserWorkItem(_ => BackgroundMethod("第二、ThreadPool创建线程"));

 

第三、delegate(委托)

  委托异步回调方法创建线程,只需调用BeginInvoke委托和触发线程。然后,调用EndInvoke将阻塞当前线程。

  

BackgroundMethodDelegate x = new BackgroundMethodDelegate(BackgroundMethod);
            IAsyncResult a = x.BeginInvoke("第三、delegate委托", null, null);
            x.EndInvoke(a);

 

第四、BackgroundWorker类

  在单独线程上执行操作

  

BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += delegate { BackgroundMethod("第四、BackGroundWorker创建线程"); };
            worker.RunWorkerAsync();

 

第五、System.Threading.Timer

  创建一个计时器,提供以指定时间间隔执行方法机制。

Timer timer = new System.Threading.Timer(_ => BackgroundMethod("第五、Timer计时器"), null, 0, Timeout.Infinite);

 

第六、Task类

  最简单的任务异步操作

  

using (Task task = new Task(() => BackgroundMethod("第六、Task类创建异步任务")))
            {
                task.Start();
                task.Wait();
            }

 

第七、Task.Factory(Task另外一种创建方式)

  创建实例工厂的访问

Task.Factory.StartNew(() => BackgroundMethod("第七、Task第二种创建异步方式"));

 

第八、Parallel类

   System.Threading.Tasks命名空间下的,提供对并行循环和区域支持

Parallel.Invoke(() => BackgroundMethod("第八、Parallel类"));

 

第九、System.Reactive.Linq.Observable

  Reactive Extensions 概要

  Reactive Extensions (下面简称 Rx) 是在 Linq 可操作的数据源上针对 "异步"(BeginXXX/EndXXX) 和 "事件"(XXXCompleted) 上的扩展,也可以被称为 "Linq To Asynchronous" 和 " Linq To Events"。相比以前复杂的异步处理或者事件处理,Timer的处理等,结合Linq 形式的Rx编程模型更加简洁。

  关于 Rx 的安装,可以通过 Reactive Extensions (Rx) 的主页 的直接下载安装,当然也可以利用 NuGet 导入 dll (http://nuget.org/packages/Rx-Main) [译注: NuGet 是VS集成的在线 dll部署工具,非常方便]。Rx 不管是 Installer 还是 NuGet 安装的,都有 Stable(稳定版) 和 Experimental(实验版) 两种。

  

Observable.Return("第九、Observable类", Scheduler.Default).Subscribe(BackgroundMethod);

 

第十、ProcessStartInfo类

  指定启动进程时使用的一组值,严格上应该不处于创建线程这一栏,但已被建议作为一种方式在后台做一些事情,即使它没有资格作为一个后台线程。 (根据定义,一个后台线程是进程中的一个线程不会防止进程终止,而它仍然在运行。 )

复制代码
ProcessStartInfo startInfo = new ProcessStartInfo("StartThreads.exe", "OutOfProcess");
            startInfo.CreateNoWindow = false;
            startInfo.UseShellExecute = false;
            startInfo.RedirectStandardOutput = true;
            Process process = Process.Start(startInfo);
            Console.WriteLine(“第十:ProcessStartInfo”);
            process.WaitForExit();
复制代码

 测试源码地址:http://files.cnblogs.com/xchit/StartThreads.rar


Qt中提供了多种线程创建方式,以下为详细介绍: 1. **继承`QObject`并使用`moveToThread`方法**:先声明一个`QObject`的子类并实现`run()`方法作为线程入口点,创建`QThread`对象,将自定义的`QObject`子类对象加入到新创建的`QThread`中,连接线程的信号和槽,最后启动线程。示例代码如下: ```cpp #include <QObject> #include <QThread> #include <QDebug> class MyThread : public QObject { Q_OBJECT public slots: void run() { qDebug() << "Thread started"; // 执行线程的操作 } }; #include "main.moc" int main(int argc, char *argv[]) { QThread *thread = new QThread(); MyThread *myThread = new MyThread(); myThread->moveToThread(thread); QObject::connect(thread, &QThread::started, myThread, &MyThread::run); QObject::connect(myThread, &MyThread::finished, thread, &QThread::quit); QObject::connect(myThread, &MyThread::finished, myThread, &MyThread::deleteLater); QObject::connect(thread, &QThread::finished, thread, &QThread::deleteLater); thread->start(); return 0; } ``` 这种方式将自定义的任务逻辑封装在`QObject`子类中,然后将其移动到新线程里执行,可灵活控制线程的生命周期和任务执行顺序[^1]。 2. **继承`QThread`类**:`Core`模块中的`QThread`类能开启一个子线程,需子类继承`QThread`并实现`run()`方法。继承自`QThread`类的子类只有其`run`方法中的对象或数据运行在新的子线程中,其它成员仍然运行在创建`QThread`子类的线程中。示例代码如下: ```cpp #include <QThread> #include <QDebug> class MyThread : public QThread { protected: void run() override { qDebug() << "Thread started"; // 执行线程的操作 } }; int main(int argc, char *argv[]) { MyThread thread; thread.start(); return 0; } ``` 该方式通过继承`QThread`并重写`run`方法,将线程的执行逻辑放在`run`方法中,使用起来较为直接,但对线程的控制相对复杂[^2]。 3. **使用`QThread::create`方法**:可以使用`QThread::create`创建线程,示例代码如下: ```cpp #include <QThread> #include <QDebug> class MCSTCommunicateService { public: void sendDeviceConfigParam(int deviceCode) { qDebug() << "Sending device config param for device code:" << deviceCode; } }; int main(int argc, char *argv[]) { MCSTCommunicateService service; int deviceCode = 1; QThread* thread = QThread::create(&MCSTCommunicateService::sendDeviceConfigParam, &service, deviceCode); QObject::connect(thread, &QThread::finished, thread, &QObject::deleteLater); thread->start(); return 0; } ``` 此方法可以方便地创建一个线程并执行指定的函数,同时可以自动管理线程的生命周期[^3]。 4. **使用`std::thread`**:可以结合标准库中的`std::thread`来创建线程,示例代码如下: ```cpp #include <QDebug> #include <thread> class MCSTCommunicateService { public: void sendDeviceConfigParam(int deviceCode) { qDebug() << "Sending device config param for device code:" << deviceCode; } }; int main(int argc, char *argv[]) { MCSTCommunicateService service; int deviceCode = 1; std::thread sendConfigThread(&MCSTCommunicateService::sendDeviceConfigParam, &service, deviceCode); sendConfigThread.detach(); return 0; } ``` 这种方式利用了标准库的线程功能,与Qt的集成度相对较低,但可以在需要时结合使用[^3]。 5. **使用`QtConcurrent`命名空间**:使用`QtConcurrent::run`可以方便地在后台线程执行任务,示例代码如下: ```cpp #include <QDebug> #include <QtConcurrent/QtConcurrent> int main(int argc, char *argv[]) { QFuture<void> future = QtConcurrent::run([&]() { qDebug() << "Running task in background thread"; }); return 0; } ``` 该方式可以简化多线程编程,提高多线程性能和易用性,适合执行一些简单的后台任务[^1][^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值