0

Good day everyone, I need to say firstly, that I am not a C# developer in anyway, I have been tasked from my boss to "Make it work".

What I want is to have a thread that will spin off, not interrupt main(), call a function CcnDirSearch() and re perform this action after a certain amount of time.

My code currently runs in console about 1 time (sometimes 6 times) and then stops. I think the threads(or something like this) are ending before the function is completing.

Here is my code:

 public int Run()
        {
            Task.Factory.StartNew(() => CcnDirFireAway());
...
...
//continues main();

>

public void CcnDirFireAway()
        {
            if (ScanDir != "")
            {   
                Console.WriteLine("Starting Initial Scan on Directory: " + ScanDir + "\n\n\n");
                TimerCallback tmCallback = CheckEffectExpiry;
                Timer timer = new Timer(tmCallback, "test", 1000, 1000);
            }
        }

>

public void CheckEffectExpiry(object objectInfo)
        {
            //TODO put your code 
            Console.ForegroundColor = ConsoleColor.Green;
            Console.Write(DateTime.Now + " Starting Scan.....\n");
            Console.ForegroundColor = ConsoleColor.White;

//Here is a call to my function that I want to call.
// I noticed that If I don't call it the programs continues to run harmoniously 
            Searcher.CcnDirSearch(ScanDir);

            Console.ForegroundColor = ConsoleColor.Red;
            Console.Write(DateTime.Now + " Finished Scan.....\n");
            Console.ForegroundColor = ConsoleColor.White;
        }

> Here is the code of the function I need to call off .

public static void CcnDirSearch(string sDir)
    {

        try
        {
            foreach (string file in Directory.EnumerateFiles(sDir, "*.*", SearchOption.AllDirectories))
            {


                    using (var stream = File.OpenRead(file))
                    {



                       // Console.WriteLine(DateTime.Now + " Checking File : " + file);
                        bool Mcard  = Searcher.CCNSearch(file, De.Thekid.INotify.Runner.MASTERCARD, false);
                        bool VCARD  = Searcher.CCNSearch(file, De.Thekid.INotify.Runner.VISA, false);
                        bool ACARD  = Searcher.CCNSearch(file, De.Thekid.INotify.Runner.AMEX, false);

                        if (Mcard)
                        {
                            Console.WriteLine(DateTime.Now + " MasterCard Number Found In File  >> " + file);
                            //Inotifywatch.EventForward.UDPSend(512, RServer, ("<30>" + DateTime.Now + " MasterCard Number Found In File  >> " + fullpath+ "\n"));
                            Logger.WriteEvent(DateTime.Now + " MasterCard Number Found In File  >> " + file + "\n");

                        }
                        else if (VCARD)
                        {
                            Console.WriteLine(DateTime.Now + " Visa Card  Number Found In File  >> " + file);
                            //Inotifywatch.EventForward.UDPSend(512, RServer, ("<30>" + DateTime.Now + " Visa Card Number Found In File  >> " + fullpath+ "\n"));
                            Logger.WriteEvent(DateTime.Now + " Visa Card Number Found In File  >> " + file + "\n");

                        }

                        else if (ACARD)
                        {
                            Console.WriteLine(DateTime.Now + " AMEX Card  Number Found In File  >> " + file);
                            //Inotifywatch.EventForward.UDPSend(512, RServer, ("<30>" + DateTime.Now + " AMEX Card Number Found In File  >> " + fullpath+ "\n"));
                            Logger.WriteEvent(DateTime.Now + " Amex Card Number Found In File  >> " + file + "\n");


                        }

                }


            }
        }
        catch (System.Exception excpt)
        {
            Console.WriteLine(excpt.Message);
        }
        Console.Write("Finished the Search\n");
    }
LUser
  • 1,127
  • 4
  • 23
  • 39
  • 1
    Gotta love bosses like that - OK there are multitudes of methods to do what you wanted, with pros and cons of all, have you had a look at any examples? – BugFinder Jul 17 '18 at 08:58
  • yes, I have and my code works, just it will eventually die. I will edit my question to reflect this. – LUser Jul 17 '18 at 09:04
  • You don't need a thread/task if you just want to spawn a timer which won't run on this thread anyway. In this case you could just directly call CcnDirFireAway in your Main without affecting performance. That being said, how long does a search take? Could it be that it takes longer than your 1s interval and there are some concurrency affects? What happens if you do `Task.Run(async () => while (true) { CheckEffectExpiry(); await Task.Delay(1000); });`? This would create a task/thread with a loop running your search on this thread, then wait 1s, restarts the search, and so on. – ckuri Jul 17 '18 at 09:09
  • @ckuri I have thought about this and I have set different timings and it doesn't appear to make a difference. – LUser Jul 17 '18 at 09:50
  • https://msdn.microsoft.com/en-us/library/dd537614(v=vs.110).aspx – Hans Passant Jul 17 '18 at 10:44

2 Answers2

0

You could use a DispatcherTimer to call a function on a given time interval, then in that function create and start a new Thread in which you execute your function.

public static void Main(string[] args)
{
    DispatcherTimer timer = new DispatcherTimer();
    timer.Interval = TimeSpan.FromMilliseconds(5000);;
    timer.IsEnabled = true;
    timer.Tick += OnTimerTick;
}

private void OnTimerTick(object sender, EventArgs e)
{
    var thread = new Thread(new ThreadStart(()=>yourMethodToCall()));
    thread.Start();
}
AndrejH
  • 2,028
  • 1
  • 11
  • 23
  • This doesn't appear to pass control to OnTimerTick or it isn't ever called. when I do this. – LUser Jul 17 '18 at 09:55
  • https://stackoverflow.com/questions/19351473/dispatchertimer-doesnt-work-in-console. According to this, it doesn't work for console applications. – LUser Jul 17 '18 at 10:36
0

I want to Thanks everyone for all your help. I found a work around that worked for me.

As I said before , I am not a C# developer (I play one on T.V) so I am certain there are somethings where this code base can be improved .

If someone can write a better answer, I will happily accept it.

I just decided to launch the code differntly .

Timer x = new Timer(state => CheckEffectExpiry(1), null, 5000 /* When to start*/, 300000 /* when to retry */);

>

 public void CheckEffectExpiry(object objectInfo)
        {

            //I hate C#'s way of accessing variables and such .
            //So I am doing this...
            Console.Write(DateTime.Now + " I was hit\n");
            if (lockf == 1)
            {

            Console.ForegroundColor = ConsoleColor.Green;
            Console.Write(DateTime.Now + " Starting Scan.....\n");
            Console.ForegroundColor = ConsoleColor.White;

                lockf = 0;
                Searcher.CcnDirSearch(ScanDir);
                lockf = 1;


            Console.ForegroundColor = ConsoleColor.Red;
            Console.Write(DateTime.Now + " Finished Scan.....\n");
            Console.ForegroundColor = ConsoleColor.White;
            }

        }
LUser
  • 1,127
  • 4
  • 23
  • 39