Gibs Gibs -3 years ago 207
C++ Question

How to use std::thread inside a member function of an object in UWP C++/CX

How to create a thread using

for UWP applications? Sorry I am having problem with the syntax needed for creating a thread of member function inside an object. I just started using c++/cx in visual studio. Here is my code:

void MainPage::increment(int val)
for (int i = 0; i < val; ++i){
textBox4->Text = m_timer4.ToString();

void _4ThreadsUWP::MainPage::button_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
std::thread th(&MainPage::increment, this, 5);


I am having these errors:


'std::invoke': no matching overloaded function found


Failed to specialize function template 'unknown-type std::invoke(_Callable &&,_Types &&...)'

Answer Source

I don't know exactly what's wrong with your constructor call - the bind-style syntax is notoriously quirky and gives the worst possible error messages.

My suggestion is to avoid std::bind and its unholy brethren (such as this std::thread constructor) altogether, and just use lambda functions whenever possible. They have their own quirks, but they are generally more understandable, error messages aren't complete garbage and they have way more applications.

In this case, you can just do:

std::thread th([this]{this->increment(5);});

That being said, your code is wrong logically on multiple levels.

As already stated into a comment, since your thread goes immediately out of scope, you are going to get an exception because std::thread doesn't want to be destroyed until the thread ended or you explicitly detach the created thread from the thread object. So:

  • either you call join, which in this case would make no sense, as now your main thread would be stalled waiting for the worker thread, so launching the thread is useless in first place;
  • or you detach it, which is bad because now you can have runaway threads; if you close the application window, you may still have the thread running, operating on data that is being destroyed.

A better solution would be to move the worker thread at class level, start it (if it's not already started) on button click and join it at window close.

But: all this is useless anyway, since in almost every GUI toolkit (including UWP) the GUI objects aren't thread safe. Invoking their methods from a thread that is not the main UI thread results in erratic behavior and crashes, and your code does exactly that.

There are ways to make safe cross-thread GUI calls (which generally boil down to passing messages through the GUI event queue) - this article may have some UWP-related suggestions - but it's like shooting mosquitoes with artillery cannons; in your case all you need is just a regular timer, with no thread whatsoever.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download