locked
Why cannot change the property in async function.

    Question

  • Hi all,

    I try to change the binding property in a async operator, but get the access violation error.

    I follow the DataBingidng sample codes, and add these codes 

    IAsyncAction^ TestWithProgressAsync(Employee^ employee)
    {
        return create_async([&employee]() {
          employee->Organization="Google";
        });
    }
    
    
    void ScenarioOutput3::Reset()
    {
    	_employee = ref new Employee();
    	_employee->Name = "Alnur Ismail";
    	_employee->Organization = "MSFT";
    	_employee->PropertyChanged += ref new PropertyChangedEventHandler(this, &ScenarioOutput3::employeeChanged);
    	this->DataContext = _employee;
    	tbBoundDataModelStatus->Text = "";
    	task<void>(TestWithProgressAsync(_employee)).then([](){
    	int a=6;
    	});
    
    }

    Does the async function cannot access the UI binding property?


    NEU_ShieldEdge

    Wednesday, May 16, 2012 12:26 PM

Answers

  • Luke,

    You should never capture a parameter to a function by reference into a lambda that is expected to run asynchronously. By the time that async lambda executes, employee is pointing to some random location on a different threads stack, which is why you see the access violation.

    Try making that

    IAsyncAction^ TestWithProgressAsync(Employee^ employee)
    {
        return create_async([employee]() {
          employee->Organization="Google";
        });
    }
    

    You can capture employee by value because its reference counted.
    • Marked as answer by Jesse Jiang Thursday, May 24, 2012 7:10 AM
    Friday, May 18, 2012 1:51 AM

All replies

  • Hello,

     

    Thanks for your feedback, I will involve more experts to investigate it.

     

    Best regards,

    Jesse


    Jesse Jiang [MSFT]
    MSDN Community Support | Feedback to us

    Thursday, May 17, 2012 7:56 AM
  • Luke,

    You should never capture a parameter to a function by reference into a lambda that is expected to run asynchronously. By the time that async lambda executes, employee is pointing to some random location on a different threads stack, which is why you see the access violation.

    Try making that

    IAsyncAction^ TestWithProgressAsync(Employee^ employee)
    {
        return create_async([employee]() {
          employee->Organization="Google";
        });
    }
    

    You can capture employee by value because its reference counted.
    • Marked as answer by Jesse Jiang Thursday, May 24, 2012 7:10 AM
    Friday, May 18, 2012 1:51 AM