Multithreading 为什么线程池工作项在UI线程上执行?
在Windows应用商店应用程序中运行的以下代码会将UI阻塞30秒,尽管循环应该在单独的线程中运行:Multithreading 为什么线程池工作项在UI线程上执行?,multithreading,windows-runtime,winrt-async,wrl,Multithreading,Windows Runtime,Winrt Async,Wrl,在Windows应用商店应用程序中运行的以下代码会将UI阻塞30秒,尽管循环应该在单独的线程中运行: int seconds(30); // Create a thread pool ComPtr<IThreadPoolStatics> threadPool; HRESULT hr = GetActivationFactory(HStringReference(RuntimeClass_Windows_System_Threading_ThreadPool).Get(), &
int seconds(30);
// Create a thread pool
ComPtr<IThreadPoolStatics> threadPool;
HRESULT hr = GetActivationFactory(HStringReference(RuntimeClass_Windows_System_Threading_ThreadPool).Get(), &threadPool);
//
// Create an asynchronous task and start it
ComPtr<ABI::Windows::Foundation::IAsyncAction> asyncActionPtr;
hr = threadPool->RunAsync(Callback<IWorkItemHandler>( // Line 1
//
// Lambda for task. Loops doing nothing until 30 seconds have passed
[seconds](ABI::Windows::Foundation::IAsyncAction* asyncAction) -> HRESULT {
std::chrono::system_clock::time_point end(std::chrono::system_clock::now() + std::chrono::seconds(seconds)); // Line 3
while (std::chrono::system_clock::now() < end);
return S_OK; // Line 4
}).Get(), &asyncActionPtr);
if (FAILED(hr)) throw std::exception("Cannot start thread"); // Line 2
int秒(30);
//创建一个线程池
ComPtr线程池;
HRESULT hr=GetActivationFactory(HStringReference(RuntimeClass\u Windows\u System\u Threading\u ThreadPool).Get(),&ThreadPool);
//
//创建一个异步任务并启动它
ComPtr异步操作ptr;
hr=threadPool->RunAsync(回调(//第1行
//
//任务的Lambda。循环在30秒之前不执行任何操作
[秒](ABI::Windows::Foundation::IAsyncAction*asyncAction)->HRESULT{
std::chrono::system_clock::time_point end(std::chrono::system_clock::now()+std::chrono::seconds(seconds));//第3行
while(std::chrono::system_clock::now()
当我在标记的行中设置断点时,我可以看到第1行在第2行之前被击中,然后是第3行,30秒后是第4行。在这30秒内,UI被阻止,VisualStudio中的线程视图为所有断点显示相同的线程(SHcore.dll)。
我正在使用Windows 8和Visual Studio 2012。
有人能解释一下吗?比尔·梅斯默在这个问题上给出了完美的答案。简言之: 回调创建的委托对象不是敏捷的,这意味着它不能传递给线程池线程。相反,该线程接收一个代理,并将对它的调用封送回UI线程中的delgate对象。比尔也给了这个问题一个简单的解决办法