Harun
Harun

Reputation: 5179

windows service fails to start while using a process to execute an exe file through c#.net

I am using a windows service to execute ffmpeg.exe for converting video files. I do this by staring a process in c#.net. The problem is that

My code within the OnStart() of windows service is as follows:

FilArgs = string.Format("-i {0} -ar 22050 -qscale 1 {1}", InputFile, OutputFile);

Process proc;
proc = new Process();

try
{
    proc.StartInfo.FileName = spath + "\\ffmpeg\\ffmpeg.exe";
    proc.StartInfo.Arguments = FilArgs;
    proc.StartInfo.UseShellExecute = false;
    proc.StartInfo.CreateNoWindow = false;
    proc.StartInfo.RedirectStandardOutput = true;
    proc.StartInfo.RedirectStandardError = true;

    eventLog1.WriteEntry("Going to start process of convertion");

    proc.Start();

    string StdOutVideo = proc.StandardOutput.ReadToEnd();
    string StdErrVideo = proc.StandardError.ReadToEnd();

    eventLog1.WriteEntry("Convertion Successful");
    eventLog1.WriteEntry(StdErrVideo);               

}
catch (Exception ex)
{
    eventLog1.WriteEntry("Convertion Failed");
    eventLog1.WriteEntry(ex.ToString());            
}
finally
{
    proc.WaitForExit();
    proc.Close();
}

when i tried to convert large video files (i experienced it when the file size is >14MB) as mentioned above the service fails to start and is in the status "starting".

The ffmpeg while running directly through command prompt works fine for larger files as well.

Any one please me how to solve this...

Upvotes: 0

Views: 602

Answers (1)

Aliostad
Aliostad

Reputation: 81660

That is bad because onstart() should only start a background thread for the worker loop. OnStart() should return pretty much immediately so no time consuming work must be done in there.

Windows waits for OnStart() to return within a timeout and if it does not, will kill it.

Basically you start a thread in there:

private Thread _workerThread;
private bool _closing = false;
... OnStart(...)
{
     _workerThread = new Thread(new ThreadStart(Work));
     _workerThread .Start();

}

private void Work()
{
    while(!_closing)
    {
    // do the processing if there is work otherwise sleep for say 10 seconds 
    }
}


... OnStop(...)
{
    _closing = true;
    _workerThread.Abort()
}

Upvotes: 5

Related Questions