简体   繁体   English

如何等待任务执行结束以恢复程序执行

[英]How to wait for the end of the execution of a task to resume the execution of a program

I'm working on ac# program where I want to wait for the end of the execution of two tasks (which run a javscript script on a browser and then use the result) to resume the execution of the main program. 我正在开发ac#程序,在这里我想等待两个任务(在浏览器上运行javscript脚本,然后使用结果)执行结束以恢复主程序的执行。 I must do that because the rest of the program necesitates the informations obtained from the browser. 我必须这样做,因为该程序的其余部分都需要从浏览器获得的信息。 I'm calling the method where the tasks are created from the main method. 我正在调用从main方法创建任务的方法。

I've tried to simply use the waitAll() method of the Task class however it seems that the execution of my program does not wait for the end of the execution of the tasks to resume. 我试图简单地使用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
  ...

} }

Your code seems correct to me. 您的代码对我来说似乎是正确的。 Could you try waiting the two tasks independently and see what happens? 您可以尝试分别等待两个任务,然后看看会发生什么吗?

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 => { ... });
}

Another way to do it: 另一种方法是:

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.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM