Straw.Hat
Straw.Hat

Reputation: 21

Concurrency::create_task throws runtime exception in VisualStudio clr project

I'm new in VisualStudio and visual c++. I'm trying to use Concurrency::create_task function in MFC project.

I created clr prject, created simple form and create new class to manage tasks. And i had to set Common Language Runtime Support to No Common Language RunTime Support to use tasks in this class.

Class header testtest.h:

#pragma once
class testtest
{
public:
    testtest();
};

and testtest.cpp:

#include "testtest.h"
#include <ppltasks.h>

using namespace Concurrency;

testtest::testtest()
{
    auto task1 = create_task([]() -> int
    {
        return 42;
    });
}

When i launch my app, it throws runtime exception (i don't even create testtest class instance)

Program: C:\projects\c\Project1\Debug\Project1.exe
File: minkernel\crts\ucrt\src\appcrt\heap\debug_heap.cpp
Line: 1037

Expression: _CrtIsValidHeapPointer(block)

Everything works fine if i create win32 console project. Spent a lot of time to reolve this, but now i have no idea what i'm doing wrong.

Any suggestions?

Upvotes: 1

Views: 757

Answers (1)

Ami Tavory
Ami Tavory

Reputation: 76297

The function

testtest::testtest()
{
    auto task1 = create_task([]() -> int
    {
        return 42;
    });
}

contains a race: the task object is created, the task is run, meanwhile the function exits and the destructor is called.

To remove the race, use wait or get:

testtest::testtest()
{
    auto task1 = create_task([]() -> int
    {
        return 42;
    });

    // Uncomment one of the following
    // task1.get();
    // task1.wait();
}

A race is, well, a race - changing the build conditions (or basically anything else), can change how it runs. Race conditions should be eliminated.

Upvotes: 1

Related Questions