C# wait until its completed

2020-05-05 17:24发布

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 receive and I can't continue until I get them and only solution I figured up was using while until I receive those values.

I'm looking for better solution. The best if it wouldn't freeze my app. It has been told me I should use events, but I couldn't figure out how to do that.

IsBusy = true;            
do
{
  if (IsBusy)
  {
    //waiting for values which i don't know when i receive
    //i can receive those values in 1sec and also in 2 min

    if done -> IsBusy = false;
  }

  Thread.Sleep(2000);

} while (IsBusy);


IsBusy = true;
do
{
  if (IsBusy)
  {
   //waiting for similar thing until i receive it

   if done -> IsBusy = false;
  }

  Thread.Sleep(5000);

} while (IsBusy);  

标签: c# winforms
2条回答
家丑人穷心不美
2楼-- · 2020-05-05 17:47

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
}
查看更多
老娘就宠你
3楼-- · 2020-05-05 18:09

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!)

查看更多
登录 后发表回答