简体   繁体   English

C#中的侦听器和控制流

[英]Listeners in and control flow in C#

How does a called function let the calling function know that he's done with all it's processing? 被调用函数如何让调用函数知道他已完成所有处理?

myFunction1(){

    myFunction2();

}

myFunction2(DownloadStringCompletedEventHandler callback){

    // Calls a web service and updates local files

}

myFunction2Returned(object sender, DownloadStringCompletedEventArgs e){


}

Start the whole call like this: 像这样开始整个通话:

myFunction1();

// Continue processing here...

Now what I want to know is, if I call myFunction1() , how can you wait untill everything in myFunction2() has finished before you carry on with your processing? 现在,我想知道的是,如果我调用myFunction1() ,如何继续进行myFunction2()所有操作,然后再继续进行处理呢? (that being whatever lies beyond the 'continue processing here...' comment). (除了“在此处继续处理...”注释之外)。

The problem is that after I call myFuntion1() my code after that tries to read files that rely on myFunction2() to have completed it's web service call and completely written the needed files to disk. 问题是,在我调用myFuntion1()之后,我的代码尝试读取依赖于myFunction2()来完成它的Web服务调用,并将所需的文件完全写入磁盘。

I hope all this makes sense, was pretty difficult getting the wording right for the question to make sense. 我希望所有这些都是有道理的,很难使措词正确无误才有意义。

You need to use async and await. 您需要使用异步并等待。 You can write a function like this: 您可以编写如下函数:

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

As is in your case, this is especially useful for things like web service access where you don't have control over the processing of the other function. 就像您的情况一样,这对于诸如Web服务访问之类的事情特别有用,因为您无法控制其他功能的处理。 The keywords here are async and await which signal that the function is going to involve asynchronous programming. 此处的关键字是asyncawait ,表示该函数将涉及异步编程。

Note that this syntax is relatively new (C#5), but since you didn't tag any specific version of .NET in your question I figured I would give you the latest and greatest ;). 请注意,这种语法是相对较新的(C#5),但是由于您没有在问题中标记任何特定版本的.NET,所以我想我会为您提供最新最好的;)。

You should use some tasks techniques for this, 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.");
}

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

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