Skip to main content
 首页 » 编程设计

c#之ContinueWith 作为 await 运算符的替代

2024年02月06日11bhlsheji

我的应用程序使用脚本。到目前为止,我已将 C# 用于脚本并使用 CodeDomProvider 编译它们.但是,我一直在考虑使用 NLua 切换到 Lua fork(LuaInterface 的一个分支),因为使用它编写脚本要容易得多,而且我熟悉语法。

但是,我遇到了一个问题。目前,我有一个 asynchronous返回 Task<bool> 的方法.它使用 TaskCompletionSource对象并返回它的 Result .这样,我就可以停止脚本的执行,因为它会一直等到 Result。的 TaskCompletionSource对象已设置,然后才返回此 Result .

现在,有了 Lua,情况就不同了。我显然不能使用 await运算符,因为它是 C# 5.0 的语法,你不能在 Lua 中使用它。所以这就是为什么我要问是否有解决方法。我希望能够在不使用 await 的情况下获得与我的旧代码(发布在这篇文章下方)相同的结果。运算符(operator)。我被告知我可以用 Task.ContinueWith 做到这一点,但我对此不熟悉,在线示例也很乏味。如果有人能用我的代码向我展示一个示例,那就太好了。

这是我的方法:

public async Task<bool> ReturnResult() 
{ 
     this.Response = new TaskCompletionSource<bool>(); 
 
     return await this.Response.Task; 
} 

这是我在脚本中使用它的方式:

var result = await ReturnResult(); 

Result的 TaskCompletionSource对象由我的代码的另一部分设置。

基本上,如果您仍然无法理解我想要实现的目标 - 一种停止执行直到代码的另一部分设置响应的方法。但是,它必须是 asynchronous ,因为我不想让我的主线程卡住。

编辑: 尝试了 JonSkeet 的建议,代码只是不停地运行。这是完整的脚本类。

public class Script 
{ 
    private Lua Lua { get; set; } 
    private TaskCompletionSource<bool> Response { get; set; } 
 
    public Script() 
    { 
        this.Lua = new Lua(); 
    } 
 
    public void Run() 
    { 
        this.Lua.RegisterFunction("log", this, typeof(Script).GetMethod("Log")); 
        this.Lua.RegisterFunction("returnResult", this, typeof(Script).GetMethod("ReturnResult")); 
 
        this.Lua.DoFile(@"C:\test.lua"); 
    } 
 
    public void SetResponse(bool response) 
    { 
        this.Response.SetResult(response); 
    } 
 
    public Task<bool> ReturnResult() 
    { 
        this.Response = new TaskCompletionSource<bool>(); 
 
        return this.Response.Task; 
    } 
 
    public void Log(string text) 
    { 
        MessageBox.Show(text); 
    } 
} 

这是 Form1 的代码:

 public partial class Form1 : Form 
{ 
    private Script Script { get; set; } 
 
    public Form1() 
    { 
        InitializeComponent(); 
    } 
 
    private void button1_Click(object sender, EventArgs e) 
    { 
        this.Script = new Script(); 
 
        this.Script.Run(); 
    } 
 
    private void button2_Click(object sender, EventArgs e) 
    { 
        this.Script.SetResponse(true); 
    } 
} 

只需扔两个按钮,使用第一个运行,第二个设置响应。

Lua脚本是:

result = returnResult() 
log("returned " .. result) 

下载NLua从这里开始。

请您参考如下方法:

好吧,既然你现在声称这与 Lua 无关,下面是你将如何在 C# 中调用该方法,然后仅在任务完成时记录:

Task<bool> task = ReturnResult(); 
task.ContinueWith(t => Log("Returned " + t.Result)); 

这根本不会停止执行 - 它只是说当从 ReturnResult 返回的任务完成时,它应该调用日志记录代码。

对于生产代码,您可能希望检查任务是否出错等。 ContinueWith 的重载允许您指定要在何种情况下运行延续(仅在成功,仅在故障时等),并且您可以添加多个延续。但要让您继续前进,以上内容可能就足够了。