Reputation: 1746
I have this code:
private void timer1_Tick(object sender, EventArgs e)
{
#region BaseAddress
Process[] test = Process.GetProcessesByName(process); //Get process handle
if (test.Any())
{
int Base = test[0].MainModule.BaseAddress.ToInt32();
}
#endregion
//lots of other code blocks
}
I now want to take the region 'BaseAddress' out of the timer1_Tick control to make the code more efficient and have it run once at the beginning of the program. The other code in this control makes frequent use of the variable 'Base', what is the best way to make this globally accessible without having to go back through all the instances that use Base and do something like MyGlobals.Base, for example?
Upvotes: 2
Views: 178
Reputation: 23123
Lazy load the address into a static variable. It won't initialize until you use it for the first time, then will remain in memory for the life of the application.
public static MyGlobals
{
private static readonly Lazy<int> _processBase = new Lazy<int>(() => GetProcessBase("MyProcessName"));
// I don't recommend using the word Base, but OK...
public static int Base { get { return _processBase.Value; } }
private static int GetProcessBase(string processName)
{
int b = 0;
Process[] p = Process.GetProcessesByName(processName);
if(p != null && p.Length > 0)
{
b = p[0].MainModule.BaseAddress.ToInt32();
}
return b;
}
}
In some other part of the app...
private void timer1_Tick(object sender, EventArgs e)
{
if(MyGlobals.Base > 0)
{
// TODO: change "Base" to "MyGlobals.Base" in code below or it won't compile...
//lots of other code blocks
}
}
Upvotes: 2
Reputation: 6814
The method I would use in this case would be to create a singleton class ProcessFetcher (for example) with a Base property.
My class would have a fetch() function and isDataPresent property.
You can decide to call fetch manually or put it on the constructor.
Upvotes: 0