Reputation: 45
As question, i need to keeps check for wheather the folder is created in 3 minutes... initially, i set myVar to 0 and everytime the timer run, it will keep add until 3 in the else part and perform the other function. Anybody can assist me in this matter as I'm not familiar in parshing data out the timers...
class Program
{
public static void Main(string[] args)
{
int myVar = 0;
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = 60000; // Currently set to 1 minutes
timer.Elapsed += (sender, e) => timer_Elapsed(sender, e, myVar);
timer.Start();
}
static void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e, int myVar)
{
DirectoryInfo imagepath = new DirectoryInfo(@"C:\Users");
DirectoryInfo[] directoryInfo = imagepath.GetDirectories();
string directoryFolderName = "";
string subdirectoryFolderName = "";
string fullPathName = "";
foreach (DirectoryInfo directory in directoryInfo)
{
directoryFolderName = directory.Name;
}
if (directoryFolderName.Contains("ABB"))
{
fullPathName = imagepath + "\\" + directoryFolderName;
DirectoryInfo path = new DirectoryInfo(fullPathName);
DirectoryInfo[] subdirectoryInfo = path.GetDirectories(); ;
foreach (DirectoryInfo subDirectory in subdirectoryInfo)
subdirectoryFolderName = subDirectory.Name;
if (subdirectoryFolderName.Contains("folder"))
{
string tempPath = fullPathName + "\\" + "folder";
mainFunction(path, imagepath);
}
else
{
Console.WriteLine(fullPathName);
Console.WriteLine("tif folder not found!!!");
string msg = "Program failed unexpectedly. Error Msg: folder not found!!!";
WriteExceptionFile(msg, null);
}
}
else
{
Console.WriteLine("Minutes: " + myVar);
myVar += 1;
}
}
Upvotes: 1
Views: 806
Reputation: 107
Use out keyword to get the updated value from your timer callback
static void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e, out int myVar)
{ ... }
This should work.
Upvotes: -1
Reputation: 136124
By default, int
is passed by value, which means when you update the variable inside your timer_elapsed
method it is not reflected outside that method.
A simple solution is to force the int to be passed by reference using the ref
keyword:
static void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e, ref int myVar){ ... }
Here's a simple demo: https://rextester.com/UOBCK74072
Upvotes: 2
Reputation: 141
You send myVar as a parameter. So, changes in method cannot changes main variables value. You can define myVar static and change it's value directly.Or you can use global variable out of main method.
static int x = 0;
static void Main(string[] args)
{
Console.WriteLine(x); // before call foo->0
foo();
Console.WriteLine(x); // after call foo -> 10
Console.ReadKey();
}
public static void foo()
{
x = 10;
}
Upvotes: 0