windows C++- WRL 使用后台线程

2024-08-25 15:04

本文主要是介绍windows C++- WRL 使用后台线程,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

由于WRL技术已经不作为主流继续发展,所以这里这个文档主要是收录WRL作为一些特殊情况下的查阅和理解windows体系开发的技术脉络,故本文档仅仅演示各项关键技术,例如本文档如何使用 Windows 运行时 C++ 模板库 (WRL) 启动异步操作并在操作完成时执行工作,而不是详细解释内部运行的机制。

本文档演示运行后台工作线程。 此示例演示如何使用返回 IAsyncInfo 接口的 Windows 运行时方法。

示例:使用后台线程

以下步骤启动工作线程并定义该线程执行的操作。此示例演示如何使用 ABI::Windows::Foundation::IAsyncAction 接口。 可以将此模式应用于实现 IAsyncInfo 的任何接口:IAsyncAction、IAsyncActionWithProgress、IAsyncOperation 和 IAsyncOperationWithProgress。

1. 包括 (#include) 任何所需的 Windows 运行时、Windows 运行时 C++ 模板库或 C++ 标准库头文件。

#include <Windows.Foundation.h>
#include <Windows.System.Threading.h>
#include <wrl/event.h>
#include <stdio.h>
#include <Objbase.h>using namespace ABI::Windows::Foundation;
using namespace ABI::Windows::System::Threading;
using namespace Microsoft::WRL;
using namespace Microsoft::WRL::Wrappers;

Windows.System.Threading.h 声明使用工作线程所需的类型。建议在 .cpp 文件中使用 using namespace 指令使代码更具可读性。

2. 初始化 Windows 运行时库:

// Initialize the Windows Runtime.
RoInitializeWrapper initialize(RO_INIT_MULTITHREADED);
if (FAILED(initialize))
{return PrintError(__LINE__, initialize);
}

3. 为 ABI::Windows::System::Threading::IThreadPoolStatics 接口创建激活工厂。

// Get the activation factory for the IThreadPoolStatics interface.
ComPtr<IThreadPoolStatics> threadPool;
HRESULT hr = GetActivationFactory(HStringReference(RuntimeClass_Windows_System_Threading_ThreadPool).Get(), &threadPool);
if (FAILED(hr))
{return PrintError(__LINE__, hr);
}

4.  创建一个将工作线程的完成情况同步到主应用的 Event 对象。

// Create an event that is set after the timer callback completes. We later use this event to wait for the timer to complete. 
// This event is for demonstration only in a console app. In most apps, you typically don't wait for async operations to complete.
Event threadCompleted(CreateEventEx(nullptr, nullptr, CREATE_EVENT_MANUAL_RESET, WRITE_OWNER | EVENT_ALL_ACCESS));
hr = threadCompleted.IsValid() ? S_OK : HRESULT_FROM_WIN32(GetLastError());
if (FAILED(hr))
{return PrintError(__LINE__, hr);
}

5. 调用 IThreadPoolStatics::RunAsync 方法以创建工作线程。 使用 Callback 函数定义操作。 

wprintf_s(L"Starting thread...\n");// Create a thread that computes prime numbers.
ComPtr<IAsyncAction> asyncAction;
hr = threadPool->RunAsync(Callback<IWorkItemHandler>([&threadCompleted](IAsyncAction* asyncAction) -> HRESULT
{// Print a message.const unsigned int start = 0;const unsigned int end = 100000;unsigned int primeCount = 0;for (int n = start; n < end; n++){if (IsPrime(n)){primeCount++;}}wprintf_s(L"There are %u prime numbers from %u to %u.\n", primeCount, start, end);// Set the completion event and return.SetEvent(threadCompleted.Get());return S_OK;}).Get(), &asyncAction);
if (FAILED(hr))
{return PrintError(__LINE__, hr);
}

6. 将消息输出到控制台,并等待线程完成。 所有 ComPtr 和 RAII 对象都离开范围并自动释放。 

// Print a message and wait for the thread to complete.
wprintf_s(L"Waiting for thread...\n");// Wait for the thread to complete.
WaitForSingleObjectEx(threadCompleted.Get(), INFINITE, FALSE);wprintf_s(L"Finished.\n");// All smart pointers and RAII objects go out of scope here.

以下是完整代码:

// wrl-consume-asyncOp.cpp
// compile with: runtimeobject.lib 
#include <Windows.Foundation.h>
#include <Windows.System.Threading.h>
#include <wrl/event.h>
#include <stdio.h>
#include <Objbase.h>using namespace ABI::Windows::Foundation;
using namespace ABI::Windows::System::Threading;
using namespace Microsoft::WRL;
using namespace Microsoft::WRL::Wrappers;// Prints an error string for the provided source code line and HRESULT
// value and returns the HRESULT value as an int.
int PrintError(unsigned int line, HRESULT hr)
{wprintf_s(L"ERROR: Line:%d HRESULT: 0x%X\n", line, hr);return hr;
}// Determines whether the input value is prime.
bool IsPrime(int n)
{if (n < 2){return false;}for (int i = 2; i < n; ++i){if ((n % i) == 0){return false;}}return true;
}int wmain()
{// Initialize the Windows Runtime.RoInitializeWrapper initialize(RO_INIT_MULTITHREADED);if (FAILED(initialize)){return PrintError(__LINE__, initialize);}// Get the activation factory for the IThreadPoolStatics interface.ComPtr<IThreadPoolStatics> threadPool;HRESULT hr = GetActivationFactory(HStringReference(RuntimeClass_Windows_System_Threading_ThreadPool).Get(), &threadPool);if (FAILED(hr)){return PrintError(__LINE__, hr);}// Create an event that is set after the timer callback completes. We later use this event to wait for the timer to complete. // This event is for demonstration only in a console app. In most apps, you typically don't wait for async operations to complete.Event threadCompleted(CreateEventEx(nullptr, nullptr, CREATE_EVENT_MANUAL_RESET, WRITE_OWNER | EVENT_ALL_ACCESS));hr = threadCompleted.IsValid() ? S_OK : HRESULT_FROM_WIN32(GetLastError());if (FAILED(hr)){return PrintError(__LINE__, hr);}wprintf_s(L"Starting thread...\n");// Create a thread that computes prime numbers.ComPtr<IAsyncAction> asyncAction;hr = threadPool->RunAsync(Callback<IWorkItemHandler>([&threadCompleted](IAsyncAction* asyncAction) -> HRESULT{// Print a message.const unsigned int start = 0;const unsigned int end = 100000;unsigned int primeCount = 0;for (int n = start; n < end; n++){if (IsPrime(n)){primeCount++;}}wprintf_s(L"There are %u prime numbers from %u to %u.\n", primeCount, start, end);// Set the completion event and return.SetEvent(threadCompleted.Get());return S_OK;}).Get(), &asyncAction);if (FAILED(hr)){return PrintError(__LINE__, hr);}// Print a message and wait for the thread to complete.wprintf_s(L"Waiting for thread...\n");// Wait for the thread to complete.WaitForSingleObjectEx(threadCompleted.Get(), INFINITE, FALSE);wprintf_s(L"Finished.\n");// All smart pointers and RAII objects go out of scope here.
}
/*
Output:
Starting thread...
Waiting for thread...
There are 9592 prime numbers from 0 to 100000.
Finished.
*/

这篇关于windows C++- WRL 使用后台线程的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1105884

相关文章

Java使用ANTLR4对Lua脚本语法校验详解

《Java使用ANTLR4对Lua脚本语法校验详解》ANTLR是一个强大的解析器生成器,用于读取、处理、执行或翻译结构化文本或二进制文件,下面就跟随小编一起看看Java如何使用ANTLR4对Lua脚本... 目录什么是ANTLR?第一个例子ANTLR4 的工作流程Lua脚本语法校验准备一个Lua Gramm

Java Optional的使用技巧与最佳实践

《JavaOptional的使用技巧与最佳实践》在Java中,Optional是用于优雅处理null的容器类,其核心目标是显式提醒开发者处理空值场景,避免NullPointerExce... 目录一、Optional 的核心用途二、使用技巧与最佳实践三、常见误区与反模式四、替代方案与扩展五、总结在 Java

使用Java将DOCX文档解析为Markdown文档的代码实现

《使用Java将DOCX文档解析为Markdown文档的代码实现》在现代文档处理中,Markdown(MD)因其简洁的语法和良好的可读性,逐渐成为开发者、技术写作者和内容创作者的首选格式,然而,许多文... 目录引言1. 工具和库介绍2. 安装依赖库3. 使用Apache POI解析DOCX文档4. 将解析

Qt中QUndoView控件的具体使用

《Qt中QUndoView控件的具体使用》QUndoView是Qt框架中用于可视化显示QUndoStack内容的控件,本文主要介绍了Qt中QUndoView控件的具体使用,具有一定的参考价值,感兴趣的... 目录引言一、QUndoView 的用途二、工作原理三、 如何与 QUnDOStack 配合使用四、自

C++使用printf语句实现进制转换的示例代码

《C++使用printf语句实现进制转换的示例代码》在C语言中,printf函数可以直接实现部分进制转换功能,通过格式说明符(formatspecifier)快速输出不同进制的数值,下面给大家分享C+... 目录一、printf 原生支持的进制转换1. 十进制、八进制、十六进制转换2. 显示进制前缀3. 指

使用Python构建一个Hexo博客发布工具

《使用Python构建一个Hexo博客发布工具》虽然Hexo的命令行工具非常强大,但对于日常的博客撰写和发布过程,我总觉得缺少一个直观的图形界面来简化操作,下面我们就来看看如何使用Python构建一个... 目录引言Hexo博客系统简介设计需求技术选择代码实现主框架界面设计核心功能实现1. 发布文章2. 加

C++中初始化二维数组的几种常见方法

《C++中初始化二维数组的几种常见方法》本文详细介绍了在C++中初始化二维数组的不同方式,包括静态初始化、循环、全部为零、部分初始化、std::array和std::vector,以及std::vec... 目录1. 静态初始化2. 使用循环初始化3. 全部初始化为零4. 部分初始化5. 使用 std::a

shell编程之函数与数组的使用详解

《shell编程之函数与数组的使用详解》:本文主要介绍shell编程之函数与数组的使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录shell函数函数的用法俩个数求和系统资源监控并报警函数函数变量的作用范围函数的参数递归函数shell数组获取数组的长度读取某下的

使用Python开发一个带EPUB转换功能的Markdown编辑器

《使用Python开发一个带EPUB转换功能的Markdown编辑器》Markdown因其简单易用和强大的格式支持,成为了写作者、开发者及内容创作者的首选格式,本文将通过Python开发一个Markd... 目录应用概览代码结构与核心组件1. 初始化与布局 (__init__)2. 工具栏 (setup_t

Python虚拟环境终极(含PyCharm的使用教程)

《Python虚拟环境终极(含PyCharm的使用教程)》:本文主要介绍Python虚拟环境终极(含PyCharm的使用教程),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,... 目录一、为什么需要虚拟环境?二、虚拟环境创建方式对比三、命令行创建虚拟环境(venv)3.1 基础命令3