0

I created a windows service in which the code will execute every 1 seconds

My code

if (Process.GetProcessesByName("my_process").Length > 0)
 {
   writelog("Started uploading files");
   upload_file();
   writelog("Finished uploading files");
}

I am checking whether the process is already running using GetProcessByName. It is not working because after every 1 second the the log file is getting an entry Started uploading files

So my log file will be

Started uploading files
Started uploading files
Started uploading files
Finished uploading files
Finished uploading files
Finished uploading files

What I need is

Started uploading files
Finished uploading files
Started uploading files
Finished uploading files
Started uploading files
Finished uploading files

ie. with out finishing the first cycle the service should not enter the process. Is there a way to achieve this

Sachu
  • 7,555
  • 7
  • 55
  • 94

2 Answers2

0

You could force it as a single instance application using Sytem.Threading.Mutex. Check out this question.

Community
  • 1
  • 1
grmbl
  • 2,514
  • 4
  • 29
  • 54
0

You can use Mutex for this. To avoid this problem you use it like this:

private static object _sync = new object();
.....

if (Process.GetProcessesByName("my_process").Length > 0)
{
    lock(_sync)//mutex here, so, only one thread will be able to launch this code.
    {
        if (Process.GetProcessesByName("my_process").Length > 0)
        {
            writelog("Started uploading files");
            upload_file();
            writelog("Finished uploading files");
        }
    }
}

Double check here is for performance. You can remove outter check if you want.

eocron
  • 6,885
  • 1
  • 21
  • 50