【发布时间】:2019-07-08 08:45:44
【问题描述】:
我正在尝试在异步方法回调中更新由 ref 传递给我的值。
// this Main method parameters are given and can not be changed.
public static void Main(ref System.String msg)
{
// here we should invoke an async code,
// which updates the msg parameter.
}
现在,我认识你 can not pass ref values to async methods。但我仍然想以某种方式更新该 ref 值,而不会阻塞我的 UI 线程。 对我来说,这听起来不合理,无法做到。
我尝试了什么:
// Our entry point
public static void Main(ref System.String msg)
{
Foo(msg);
}
// calls the updater (can't use 'await' on my entry point. its not 'async method')
static async void Foo(ref System.String m)
{
var progress = new Progress<string>(update => { m = update; });
await Task.Run(() => MyAsyncUpdaterMethod(progress));
}
// update the variable
static void MyAsyncUpdaterMethod(IProgress<string> progress)
{
Thread.Sleep(3000);
if (progress != null)
{
progress.Report("UPDATED");
}
}
显然,由于无法将 msg 参数超出异步方法 lambda 表达式的范围,这将不起作用。我的问题是:什么会?如何实现?
是否可以设置一个全局静态变量来保存 ref 参数,并在回调中使用它?
【问题讨论】:
-
Main是void而不是Task背后有什么原因吗? -
它是整个RAD应用程序(低代码)的一部分,它使用.net,这就是为什么我提到输入方法不能改变,它给你。
标签: c# asynchronous