参考在异步任务 [英] Ref in async Task
问题描述
我怎样才能通过参考在Windows Store应用的参数,异步方法?结果我正在寻找这样的事情:
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;
}
但是,错误:
异步方法不能有ref或out参数
Async methods cannot have ref or out parameters
有什么法子?
请注意:结果我需要传递准确obj.value。该方法通过将不同类型的对象,也可用于由同一类型的对象,一个对象,但我会把obj.val_1,obj.val_2或obj.val_10。所有的值将相同类型(前字符串)
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)
推荐答案
如果你不计较一点点开销和你的对象的可能长寿命化,你可以通过传递setter和getter方法来模拟裁判的行为功能,像这样:
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);
}
和调用它是这样的:
await DoStuff(() => obj.Value, x => obj.Value = x);
这篇关于参考在异步任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!