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);
I think best way to use async await. In C#, asynchronous programming with async await is very easy. Code looks like synchronous.
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:
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 useasync
/await
, and please select @Astemir-Almov's as the accepted answer!)