This is the kind of thing you can kick off as a background task when your application starts, eliminating the effect to startup delay.
Save this as your Program.cs
file. It should run very quickly and have 0 impact on startup time.
You will need to create a utf-8 encoded text file, one city per line, with all your cities. In this example I assume it is in the application root directory and called data.txt
but you can change this in my example code.
You can use MainNamespace.MainClass.CityExists(value)
anywhere in your application to check if an entry exists.
Obviously this is crude but effective, you could refactor it into a city service class or something...
using System.Collections.Generic;
using System.Linq;
namespace MainNamespace
{
public static class MainClass
{
private const string cityFilePath = "./data.txt"; // change to your correct path
private static HashSet<string> cities;
// use this method for city lookup checks
public static bool CityExists(string value)
{
while (cities is null)
{
// this is unlikely to trigger, the city data will probably be loaded before your first city query, but just in case...
System.Threading.Thread.Sleep(20);
}
return cities.Contains(value);
}
public static void Main()
{
Task.Run(async () =>
{
// no error handling here, you would likely want to try/catch this and do something appropriate if exception is thrown
HashSet<string> hashSet = (await File.ReadAllLinesAsync(cityFilePath)).ToHashSet(StringComparer.OrdinalIgnoreCase);
cities = hashSet;
}).GetAwaiter();
// go on executing the rest of your application, show main form, etc.
}
}
}