【问题标题】:Listeners in and control flow in C#C# 中的侦听器和控制流
【发布时间】:2012-11-05 04:15:15
【问题描述】:

被调用函数如何让调用函数知道他已完成所有处理?

myFunction1(){

    myFunction2();

}

myFunction2(DownloadStringCompletedEventHandler callback){

    // Calls a web service and updates local files

}

myFunction2Returned(object sender, DownloadStringCompletedEventArgs e){


}

像这样开始整个通话:

myFunction1();

// Continue processing here...

现在我想知道的是,如果我打电话给myFunction1(),你怎么能等到myFunction2() 中的所有内容都完成后再继续处理? (这超出了“在此处继续处理......”评论之外的任何内容)。

问题是,在我调用 myFuntion1() 之后,我的代码尝试读取依赖于 myFunction2() 的文件以完成其 Web 服务调用并将所需的文件完全写入磁盘。

我希望所有这些都是有道理的,很难让问题的措辞正确。

【问题讨论】:

  • 我很困惑。你不是已经这样了吗?
  • @J. Steen - 看看我编辑过的问题。更详细一点。
  • 如果两个函数在同一个线程上运行它应该等待

标签: c# asynchronous listener


【解决方案1】:

您应该为此使用一些任务技术,something like this

static void SimpleNestedTask()
{
    var parent = Task.Factory.StartNew(() =>
    {
        // myFunction1 code here;
        Console.WriteLine("Outer task executing.");

        var child = Task.Factory.StartNew((t) =>
        {
            // myFunction2 code here
            // Calls a web service and updates local files
            Console.WriteLine("Nested task completing.");
        }, TaskCreationOptions.AttachedToParent | TaskCreationOptions.LongRunning);
   });

    parent.Wait();
    Console.WriteLine("Outer has completed.");
}

【讨论】:

    【解决方案2】:

    您需要使用异步和等待。你可以这样写一个函数:

    private async void SomeFunction()
    {
        // Do something
        await SomeOtherFunction();
        // Do something else
    }
    

    在您的情况下,这对于您无法控制其他功能的处理的 Web 服务访问特别有用。这里的关键字是asyncawait,这表明该函数将涉及异步编程。

    请注意,这种语法相对较新(C#5),但由于您没有在问题中标记任何特定版本的 .NET,我想我会给您最新最好的;)。

    【讨论】:

    • asyncawait 只是糖,你应该知道它们发生了什么。
    猜你喜欢
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-22
    • 2012-07-11
    • 2018-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多