【问题标题】:How to wait for the end of the execution of a task to resume the execution of a program如何等待任务执行结束来恢复程序的执行
【发布时间】:2019-07-21 21:24:41
【问题描述】:

我正在开发一个 c# 程序,我想等待两个任务的执行结束(在浏览器上运行 javscript 脚本,然后使用结果)以恢复主程序的执行。我必须这样做,因为程序的其余部分需要从浏览器获得的信息。我正在调用从 main 方法创建任务的方法。

我尝试简单地使用 Task 类的 waitAll() 方法,但似乎我的程序的执行并没有等待任务执行结束才能恢复。

public void method1 () {
  Task t1 = browser.EvaluateScriptAsync(myScript1).ContinueWith(x =>{... }});
  Task t2 = browser.EvaluateScriptAsync(myScript2).ContinueWith(x =>{...});
  Task.WaitAll(t1, t2);
}

static void main (){
  method1();
  //code which necessisates the information brought by method1
  ...

}

【问题讨论】:

  • 你不是awaiting 电话。你也不应该有 async void 。这里有足够的建议你需要去了解 C# 中的await/async

标签: c# multithreading task


【解决方案1】:

您的代码对我来说似乎是正确的。你能不能试着分别等待这两个任务,看看会发生什么?

public void Method1()
{
    Task t1 = browser.EvaluateScriptAsync(myScript1);
    t1.Wait();
    // Put here the code inside the ContinueWith(x => { ... });
    Task t2 = browser.EvaluateScriptAsync(myScript2)
    t2.Wait();
    // Put here the code inside the ContinueWith(x => { ... });
}

另一种方法:

public async Task Method1Async()
{
    Task t1 = browser.EvaluateScriptAsync(myScript1);
    Task t2 = browser.EvaluateScriptAsync(myScript2);
    await t1;
    // Put here the code inside the ContinueWith(x => { ... });
    await t2;
    // Put here the code inside the ContinueWith(x => { ... });
}

static void Main()
{
    Method1Async().Wait();
    // Code which necessitates the information brought by Method1Async.
}

【讨论】:

    猜你喜欢
    • 2022-12-18
    • 2023-03-21
    • 2022-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-17
    相关资源
    最近更新 更多