当前位置:   article > 正文

[WTL/ATL]_[C/C++]_[DispatchAsync使用lambda表达式来简化发送数据到界面线程]_c++ async配合lamda表达式

c++ async配合lamda表达式

场景

  1. 在进行 Win32 界面编程时,更新界面内容只能通过主线程进行更新. 那么如果是在工作线程执行完逻辑后如何通过把数据传递给界面线程更新数据?

  2. Windows 上开发界面我是使用轻量级 Win32框架MFC 的精简版 WTL 进行开发,那么在 WTL 开发时如何把数据传递给界面?

说明

  1. 我在这篇博客里《Win32实现Cocoa的dispatch_async到主线程的异步消息处理》有写如何利用 DispatchAsync 来执行主线程任务.

  2. 在这里例子任务里,我们定义了一个全局函数, 在主线程执行函数 PrintStr。实际上我们可以利用 C++11lambda 表达式来实现函数功能,避免定义一个只用一次的函数. 可以说用 lambda 表达式我们可以使用类似同步的方式进行编码。

是不是很优雅.^_^

static DWORD WINAPI DoWorkThread(void* lpThreadParameter)
{
	auto frame = (CMainFrame*)lpThreadParameter;
	DispatchAsync(DispatchGetMainQueue(), new std::function<void()>(std::bind([](CMainFrame* frame, wchar_t* message) {
		assert(gMainThreadId == GetCurrentThreadId());
		::MessageBox(frame->m_hWnd, message, L"DoDispatchMessage Main Thread", 0);
		free(message);
	}, frame, wcsdup(L"DispatchAsync 主线程(界面线程)执行代码2-使用lambda表达式"))));
	return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  1. 我们也可以使用 std::bind 来绑定成员函数,或者绑定预定义的函数参数,非常方便。

以下例子使用在 Win32实现Cocoa的dispatch_async到主线程的异步消息处理 里使用的 DispatchAsync 工具函数来在主线程执行弹出对话框。

例子

  1. 使用 vs2017WTL 写的项目里子
  2. 在点击菜单 File 里选择 DispatchAsync, DispatchAsync2,PostMessage 对应着不同的发送消息到主线程的用法。

MainFrm.cpp

// MainFrm.cpp : implmentation of the CMainFrame class
//
/

#include "stdafx.h"
#include <iostream>
#include <atlstr.h>
#include <assert.h>
#include "resource.h"

#include "aboutdlg.h"
#include "View.h"
#include "MainFrm.h"

BOOL CMainFrame::PreTranslateMessage(MSG* pMsg)
{
	if(CFrameWindowImpl<CMainFrame>::PreTranslateMessage(pMsg))
		return TRUE;

	return m_view.PreTranslateMessage(pMsg);
}

BOOL CMainFrame::OnIdle()
{
	UIUpdateToolBar();
	return FALSE;
}

int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
	// create command bar window
	HWND hWndCmdBar = m_CmdBar.Create(m_hWnd, rcDefault, NULL, ATL_SIMPLE_CMDBAR_PANE_STYLE);
	// attach menu
	m_CmdBar.AttachMenu(GetMenu());
	// load command bar images
	m_CmdBar.LoadImages(IDR_MAINFRAME);
	// remove old menu
	SetMenu(NULL);

	HWND hWndToolBar = CreateSimpleToolBarCtrl(m_hWnd, IDR_MAINFRAME, FALSE, ATL_SIMPLE_TOOLBAR_PANE_STYLE);

	CreateSimpleReBar(ATL_SIMPLE_REBAR_NOBORDER_STYLE);
	AddSimpleReBarBand(hWndCmdBar);
	AddSimpleReBarBand(hWndToolBar, NULL, TRUE);

	CreateSimpleStatusBar();

	m_hWndClient = m_view.Create(m_hWnd, rcDefault, NULL, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, WS_EX_CLIENTEDGE);

	UIAddToolBar(hWndToolBar);
	UISetCheck(ID_VIEW_TOOLBAR, 1);
	UISetCheck(ID_VIEW_STATUS_BAR, 1);

	// register object for message filtering and idle updates
	CMessageLoop* pLoop = _Module.GetMessageLoop();
	ATLASSERT(pLoop != NULL);
	pLoop->AddMessageFilter(this);
	pLoop->AddIdleHandler(this);

	DispatchQueueInit(m_hWnd);
	return 0;
}

LRESULT CMainFrame::OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
	// unregister message filtering and idle updates
	CMessageLoop* pLoop = _Module.GetMessageLoop();
	ATLASSERT(pLoop != NULL);
	pLoop->RemoveMessageFilter(this);
	pLoop->RemoveIdleHandler(this);

	bHandled = FALSE;
	return 1;
}

LRESULT CMainFrame::OnFileExit(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
	PostMessage(WM_CLOSE);
	return 0;
}

LRESULT CMainFrame::OnViewToolBar(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
	static BOOL bVisible = TRUE;	// initially visible
	bVisible = !bVisible;
	CReBarCtrl rebar = m_hWndToolBar;
	int nBandIndex = rebar.IdToIndex(ATL_IDW_BAND_FIRST + 1);	// toolbar is 2nd added band
	rebar.ShowBand(nBandIndex, bVisible);
	UISetCheck(ID_VIEW_TOOLBAR, bVisible);
	UpdateLayout();
	return 0;
}

LRESULT CMainFrame::OnViewStatusBar(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
	BOOL bVisible = !::IsWindowVisible(m_hWndStatusBar);
	::ShowWindow(m_hWndStatusBar, bVisible ? SW_SHOWNOACTIVATE : SW_HIDE);
	UISetCheck(ID_VIEW_STATUS_BAR, bVisible);
	UpdateLayout();
	return 0;
}

LRESULT CMainFrame::OnAppAbout(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
	CAboutDlg dlg;
	dlg.DoModal();
	return 0;
}

void CMainFrame::DoDispatchMessage(wchar_t* message)
{
	assert(gMainThreadId == GetCurrentThreadId());
	MessageBox(message,L"DoDispatchMessage Main Thread",0);
	free(message);
}

static DWORD WINAPI DoDispatchWorkThread(void* lpThreadParameter)
{
	auto frame = (CMainFrame*)lpThreadParameter;
	auto callback = new std::function<void()>(std::bind(&CMainFrame::DoDispatchMessage,
		frame,wcsdup(L"DispatchAsync 主线程(界面线程)执行代码1-使用成员函数")));
	DispatchAsync(DispatchGetMainQueue(),callback);
	return NULL;
}

LRESULT CMainFrame::OnFileNew(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
	DWORD threadId = 0;
	auto handle = ::CreateThread(NULL,0,&DoDispatchWorkThread,this,0,&threadId);
	CloseHandle(handle);
	return 0;
}

LRESULT CMainFrame::OnTestPostMessage(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
	MessageBox((wchar_t*)wParam,(wchar_t*)lParam,0);
	free((wchar_t*)wParam);
	free((wchar_t*)lParam);
	return 0;
}

static DWORD WINAPI DoWorkThread(void* lpThreadParameter)
{
	auto frame = (CMainFrame*)lpThreadParameter;
	DispatchAsync(DispatchGetMainQueue(), new std::function<void()>(std::bind([](CMainFrame* frame, wchar_t* message) {
		assert(gMainThreadId == GetCurrentThreadId());
		::MessageBox(frame->m_hWnd, message, L"DoDispatchMessage Main Thread", 0);
		free(message);
	}, frame, wcsdup(L"DispatchAsync 主线程(界面线程)执行代码2-使用lambda表达式"))));
	return 0;
}

LRESULT CMainFrame::OnFileOpen(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
	DWORD threadId = 0;
	auto handle = ::CreateThread(NULL,0,&DoWorkThread,this,0,&threadId);
	CloseHandle(handle);
	return 0;
}


LRESULT CMainFrame::OnFileSave(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
	DWORD threadId = 0;
	auto func = [](LPVOID data)->DWORD {
		// 测试工作线程通过常规的通过PostMessage函数发送数据到界面线程.
		auto frame = (CMainFrame*)data;
		::PostMessage(frame->m_hWnd, USER_MESSAGE_POST_MESSAGE_1,
			(WPARAM)wcsdup(L"不使用DispatchAsync"), (LPARAM)wcsdup(L"测试PostMessage"));
		return 0;
	};

	//auto func2 = [this](LPVOID data)->DWORD {
	//	::PostMessage(m_hWnd, USER_MESSAGE_POST_MESSAGE_1,
	//		(WPARAM)wcsdup(L"不是使用DispatchAsync"), (LPARAM)wcsdup(L"测试PostMessage"));
	//	return 0;
	//};

	//auto func3 = std::function<DWORD(LPVOID)>(std::bind([](CMainFrame* frame,LPVOID data)->DWORD {
	//	::PostMessage(frame->m_hWnd, USER_MESSAGE_POST_MESSAGE_1,
	//		(WPARAM)wcsdup(L"不是使用DispatchAsync"), (LPARAM)wcsdup(L"测试PostMessage"));
	//	return 0;
	//},this,std::placeholders::_1));

	// 1. C++11只支持lambda类型到函数指针类型的转换,不支持std::function到普通函数类型的转换.
	// 2. 对于lambda表达式转换为函数指针类型,也不能使用捕抓变量特性.
	auto handle = ::CreateThread(NULL, 0, func,this ,0,&threadId);
	CloseHandle(handle);
	return 0;
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191

MainFrm.h

// MainFrm.h : interface of the CMainFrame class
//
/

#pragma once

#include <functional>
#include "platform.h"
#include "dispatch_queue.h"

class CMainFrame : 
	public CFrameWindowImpl<CMainFrame>, 
	public CUpdateUI<CMainFrame>,
	public CMessageFilter, public CIdleHandler
{
public:
	DECLARE_FRAME_WND_CLASS(NULL, IDR_MAINFRAME)

	CView m_view;
	CCommandBarCtrl m_CmdBar;

	virtual BOOL PreTranslateMessage(MSG* pMsg);
	virtual BOOL OnIdle();

	BEGIN_UPDATE_UI_MAP(CMainFrame)
		UPDATE_ELEMENT(ID_VIEW_TOOLBAR, UPDUI_MENUPOPUP)
		UPDATE_ELEMENT(ID_VIEW_STATUS_BAR, UPDUI_MENUPOPUP)
	END_UPDATE_UI_MAP()

	BEGIN_MSG_MAP_EX(CMainFrame)
		MESSAGE_HANDLER(USER_MESSAGE_POST_MESSAGE_1,OnTestPostMessage)
		MESSAGE_HANDLER(WMC_DISPATCH_MAIN_QUEUE, OnDispatchMainQueueEvent)
		MSG_WM_CREATE(OnCreate)
		MESSAGE_HANDLER(WM_DESTROY, OnDestroy)
		COMMAND_ID_HANDLER(ID_APP_EXIT, OnFileExit)
		COMMAND_ID_HANDLER(ID_FILE_NEW, OnFileNew)
		COMMAND_ID_HANDLER(ID_FILE_OPEN, OnFileOpen)
		COMMAND_ID_HANDLER(ID_FILE_SAVE, OnFileSave)
		COMMAND_ID_HANDLER(ID_VIEW_TOOLBAR, OnViewToolBar)
		COMMAND_ID_HANDLER(ID_VIEW_STATUS_BAR, OnViewStatusBar)
		COMMAND_ID_HANDLER(ID_APP_ABOUT, OnAppAbout)
		CHAIN_MSG_MAP(CUpdateUI<CMainFrame>)
		CHAIN_MSG_MAP(CFrameWindowImpl<CMainFrame>)
	END_MSG_MAP()

// Handler prototypes (uncomment arguments if needed):
//	LRESULT MessageHandler(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
//	LRESULT CommandHandler(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
//	LRESULT NotifyHandler(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/)

	LRESULT OnTestPostMessage(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);
	int OnCreate(LPCREATESTRUCT lpCreateStruct);
	LRESULT OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled);
	LRESULT OnFileExit(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
	LRESULT OnFileNew(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
	LRESULT OnFileOpen(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
	LRESULT OnFileSave(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
	LRESULT OnViewToolBar(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
	LRESULT OnViewStatusBar(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
	LRESULT OnAppAbout(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);

	void DoDispatchMessage(wchar_t* message);

	LRESULT OnDispatchMainQueueEvent(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
    {
		// std::function 使用完之后需要删除.
        std::function<void()>* func = (std::function<void()>*)wParam;
        (*func)();
        delete func;
        return 0;
    }
};

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73

dispatch_queue.h

#ifndef __DISPATCH_QUEUE_H
#define __DISPATCH_QUEUE_H

#include <Windows.h>
#include <WinUser.h>
#include <functional>
#include <atlbase.h>
#include <atlapp.h>

enum
{
    WMC_DISPATCH_MAIN_QUEUE = WM_USER+1000
};


typedef struct DispatchQueueObject1
{
    DWORD threadId;
    HWND m_hwnd;
}DispatchQueueObject;

extern void DispatchQueueInit(HWND hwnd);
extern DispatchQueueObject* DispatchGetMainQueue();
extern void DestroyMainQueue(DispatchQueueObject* object);

inline void DispatchAsync(DispatchQueueObject* queue,std::function<void()>* callback)
{
    if(queue->threadId){
        ::PostThreadMessage(queue->threadId,
        WMC_DISPATCH_MAIN_QUEUE,(WPARAM)callback,0);
    }else{
        ::PostMessage(queue->m_hwnd,
        WMC_DISPATCH_MAIN_QUEUE,(WPARAM)callback,0);
    }
	DestroyMainQueue(queue);
}

#endif
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38

dispatch_queue.h

#include "stdafx.h"

#include "dispatch_queue.h"

static HWND gMainFrameHwnd = NULL;

void DispatchQueueInit(HWND hwnd)
{
    gMainFrameHwnd = hwnd;
}

DispatchQueueObject* DispatchGetMainQueue()
{
    DispatchQueueObject* object = (DispatchQueueObject*)malloc(sizeof(DispatchQueueObject));
    memset(object,0,sizeof(DispatchQueueObject));
    object->m_hwnd = gMainFrameHwnd;
    return object; 
}

void DestroyMainQueue(DispatchQueueObject* object)
{
	free(object);
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

输出

使用 lambda 表达式代替函数

在这里插入图片描述

使用成员方法

在这里插入图片描述

使用原始的 PostMessage

在这里插入图片描述

下载

DispatchAsync使用lambda表达式来简化发送数据

参考

Win32实现Cocoa的dispatch_async到主线程的异步消息处理

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/602475
推荐阅读
相关标签
  

闽ICP备14008679号