Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ref in async Task

How I can to pass a reference as a parameter to Async method in Windows Store App ?
I'm looking for something like this:

var a = DoThis(ref obj.value);

public async Task DoThis(ref int value)
{
    value = 10;
}

But error:

Async methods cannot have ref or out parameters

Has any another way?

Note:
I need to pass exactly obj.value. This method would be used by different types of objects, by same type of objects, by one object, but I will pass obj.val_1, obj.val_2 or obj.val_10. All values will be same type (for ex string)

like image 842
jimpanzer Avatar asked May 21 '13 07:05

jimpanzer


2 Answers

If you don't care about a little overhead and possibly prolonged lifetime of your objects, you could emulate the ref behavior by passing a setter and a getter method to the function, like this:

public async Task DoStuff(Func<int> getter, Action<int> setter)
{
    var value1 = getter();
    await DoSomeOtherAsyncStuff();
    setter(value1 * value1);
}

And call it like this:

await DoStuff(() => obj.Value, x => obj.Value = x);
like image 67
Nuffin Avatar answered Sep 21 '22 23:09

Nuffin


You could directly pass the object itself and set the value of the corresponding property inside the method:

var a = DoThis(obj);

public async Task DoThis(SomeObject o)
{
    o.value = 10;
}

And if you do not have such object simply write one and have the async method take that object as parameter:

public class SomeObject
{
    public int Value { get; set; }
}
like image 30
Darin Dimitrov Avatar answered Sep 21 '22 23:09

Darin Dimitrov