'When to break a broken While loop?
I have a while loop that waits for a local setting value to no longer be null. In the event that something is borked and the value remains null, is there some sort of best practice for how you should break out of the loop? Right now I just have it counting up to 100 and if it's looped 100 times to break the loop:
int i = 0;
while (ApplicationData.Current.LocalSettings.Values["MediaInfoSaved"] == null)
{
await Task.Delay(15);
i++;
if(i >= 100)
{
break;
}
}
The loop is waiting for a process in a full trust helper to finish and return it's result. The process can take a while to complete sometimes (0.1-1 second).
Solution 1:[1]
Put the value (represented as 100 in your code) in a config file so it's easily changed if needed. If issues pop up later you can adjust it as needed.
Solution 2:[2]
If the process is expected to take up to a second, then wait for just a second. No need to loop and increment a counter:
private async Task<object> GetLocalSettingAsync()
{
const string SettingName = "MediaInfoSaved";
// Try to get the value immediately:
var setting = ApplicationData.Current.LocalSettings.Values[SettingName];
if (setting != null)
return setting;
// Wait for one second only.
await Task.Delay(TimeSpan.FromSeconds(1));
// Return either a value or null.
return ApplicationData.Current.LocalSettings.Values[SettingName];
}
If you want to exit as fast as possible but wait for up to a second, then spin in a loop and poll the property:
private async Task<object> GetLocalSettingAsync()
{
const string SettingName = "MediaInfoSaved";
DateTime start = DateTime.UtcNow;
object setting;
do
{
setting = ApplicationData.Current.LocalSettings.Values[SettingName];
if (setting != null)
break;
//optionally wait here:
await Task.Delay(15);
} while (DateTime.UtcNow.Subtract(start).TotalSeconds < 1);
return setting;
}
I am afraid it doesn't get any better unless the object that you are monitoring raises some kind of event or callback when there is data available.
Solution 3:[3]
It is very common practice to implement a timeout, where you wait a specified amount of time (if you have an idea how long the process should be taking) before breaking out of the loop. This is basically what you have implemented. If you think it shouldn't take more than 1 second to complete, make sure it breaks the loop after 1.5-2 seconds. There may be more effective ways to implement this, like using the actual time within the system.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | |
Solution 3 | Brandon O. |