November 10, 2018

ThreadPool Extensions

A better more versatile way to do this is to use Task<> objects
public static class ThreadpoolExtensions
{
    // Execute a method/procedure on the thread pool
    // The state parameters allow you to pass parameters into the thread routine 
    public static bool ExecuteOnThreadPoolThread<T>(this Action<T> threadRoutine, T args)
    {
        return ThreadPool.QueueUserWorkItem(s => threadRoutine((T)s), args);
    }

    // Execute a method/procedure on the thread pool
    public static bool ExecuteOnThreadPoolThread(this Action threadRoutine)
    {
        return ThreadPool.QueueUserWorkItem((obj) => threadRoutine());
    }
}

SImple Application Settings Manager

Heres a quick class to read and write settings to the application config file
// A Minimal class to read and write settings directly to the application 
// config file with NO write permission constraints. It does keep a separate
// copy of the config file for each user
// Only Key/Value style settings can be written, and string ones only at that but
// converting most simple types to and from a string is trivial.
public class SettingsManager : ISettingsManager
{
    public string ReadSetting(string key)
    {
        try
        {
            var appSettings = ConfigurationManager.AppSettings;
            var result = appSettings[key] ?? string.Empty;
            return result;
        }
        catch (ConfigurationErrorsException ex)
        {
            Trace.WriteLine("Configuration file exception : " + ex);
        }
        return string.Empty;
    }

    public void WriteSetting(string key, string value)
    {
        try
        {
            var configFile = ConfigurationManager.OpenExeConfiguration(
                ConfigurationUserLevel.None);
            var settings = configFile.AppSettings.Settings;
            if (settings.Count == 0 | settings[key] == null)
            {
                settings.Add(key, value);
            }
            else
            {
                settings[key].Value = value;
            }
            configFile.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection(
                configFile.AppSettings.SectionInformation.Name);
        }
        catch (ConfigurationErrorsException ex)
        {
            Trace.WriteLine("Configuration file exception : "+ ex);
        }
    }