C# wait until its completed

后端 未结 2 1907
逝去的感伤
逝去的感伤 2021-01-29 02:27

I have some code, and I have noticed it makes my app freeze. I\'m looking for a solution that is better than mine.

How to wait for values which I don\'t know when I rece

相关标签:
2条回答
  • 2021-01-29 03:02

    There may be a couple possibilities, though the description of what you're waiting on is vague enough we may not be able to point you in a specific direction. Some things that might work are:

    1. Event-based coding. If you can change the code of the process you're waiting for, you can have it raise an event that your calling code then handles. This other SO answer has a simple, complete C# program that raises and handles events.
    2. BackgroundWorker often works well in Windows Forms projects, in my experience. In my experience it's one of the simpler ways to get started with multithreading. There's a highly-rated tutorial with code samples here that may help.

    There are other ways to multithread your code, too (so that it doesn't "freeze up" while you're waiting), but these may be a simpler starting point for doing what you need.

    Async/await may work for you, but I find they're most useful when you already have an existing doSomethingAsync()-type method to work with (such as async web/WCF service methods in a .NET-generated proxy). But if all the code's your own and you're trying to multithread from scratch, they won't be the central mechanism you'd use to get started. (Of course, if it turns out you are waiting on something with a built-in ...Async() method like a web service call, by all means use async/await, and please select @Astemir-Almov's as the accepted answer!)

    0 讨论(0)
  • 2021-01-29 03:07

    I think best way to use async await. In C#, asynchronous programming with async await is very easy. Code looks like synchronous.

    private async void StartButtonClick(object sender, RoutedEventArgs e)
    {
       // Starting new task, function stops
       // the rest of the function is set to cont
       // UI not blocked
       Task.Run(async () =>
       {
            var MyValue = await doSomethingAsync();
    
        }); //there you waiting value
    
       //continue code
    }
    
    0 讨论(0)
提交回复
热议问题