This seems like it should be so simple, but apparently it isn’t.
I have a dictionary that needs to load ~40,000 entries on program startup.
It only delays load time by about 5-7 seconds, but I’d like to do it in the background to avoid this.
In the code below, there are 3 sections that deal with the dictionary and BackgroundWorkerI currently have.
I know that this code makes it to the PopulateZipCodeDictionary() method, but for some reason it doesn’t actually launch that method.
What am I doing wrong?
static BackgroundWorker populateZipCodeDictionary;
public MainWindow()
{
populateZipCodeDictionary = new BackgroundWorker();
populateZipCodeDictionary.DoWork += populateZipCodeDictionary_DoWork;
populateZipCodeDictionary.RunWorkerCompleted += populateZipCodeDictionary_RunWorkerCompleted;
populateZipCodeDictionary.RunWorkerAsync();
}
static void populateZipCodeDictionary_DoWork(object sender, DoWorkEventArgs e)
{
ZipCodes.PopulateZipCodeDictionary();
}
static void populateZipCodeDictionary_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("Dictionary loaded");
}
static class ZipCodes
{
#region Methods
public static string GetValue(string key)
{
string result;
if (zipCodeDictionary.TryGetValue(key, out result))
{
return result;
}
else
{
return null;
}
}
#endregion
#region ZipCode Dictionary Definition
static Dictionary<string, string> zipCodeDictionary = new Dictionary<string, string>();
public static void PopulateZipCodeDictionary()
{
zipCodeDictionary.Add( "00501", "Holtsville, NY" );
zipCodeDictionary.Add( "00544", "Holtsville, NY" );
zipCodeDictionary.Add( "00601", "Adjuntas, PR" );
zipCodeDictionary.Add( "00602", "Aguada, PR" );
zipCodeDictionary.Add( "00603", "Aguadilla, PR" );
zipCodeDictionary.Add( "00604", "Aguadilla, PR" );
//Continues on adding ~40k entries...
}
This is a routine I use for background processing. You simply give
RunBehindan action to perform and an action to call when processing is complete.Also maybe try locking…