Please. I need to read data from a process asynchronously because sometimes data is received indefinitely and cannot be read synchronously. When I have read enough characters, I unsubscribe from the event handlers and kill the process, returnig the value However, the data is still received in OutputDataReceived
and ErrorDataReceived
, even when the program has already exited the GetYTTitle()
function. How can I stop receiving this data in the event handlers?
Here is the function sample:
public static string GetYTTitle(string link)
{
//link example:
//https://www.youtube.com/watch?v=3QxwYWYzEis&list=RDEMF3TMXnvKDsn8vLgAp5nmdA&index=9
string standard_output = "";
int n = 0;
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.FileName = @"D:youtube-dlyt-dlp.exe";
p.StartInfo.Arguments = " --get-title " + link;
p.ErrorDataReceived += (s, e) =>
{
if (e != null)
{
Console.WriteLine(" error Ouput Data ");
Console.WriteLine(e.Data);
}
};
p.OutputDataReceived += (s, e) =>
{
if (e != null)
{
Console.WriteLine("Datos de Standard Ouput: ");
Console.WriteLine(e.Data);
standard_output += e.Data;
if (standard_output.Length > 100)
{
Console.WriteLine("Enough charactes gotten");
p.ErrorDataReceived -= (s, e)=> { };
p.OutputDataReceived -= (s, e) => { };
p.Kill();
}
}
};
p.Exited += (s, e) =>
{
Console.WriteLine("Process finished.");
p.ErrorDataReceived -= (s, e) => { };
p.OutputDataReceived -= (s, e) => { };
p.Kill();
};
p.Start();
p.BeginErrorReadLine();
p.BeginOutputReadLine();
while (!p.HasExited)
{
Thread.Sleep(1000);
n = n+1; ;
Console.WriteLine(n + " seconds elapsed of " +40);
Console.ResetColor();
if (n > 39)
{
p.ErrorDataReceived -= (s, e) => { };
p.OutputDataReceived -= (s, e) => { };
p.Kill();
return standard_output;
}
}
return standard_output;
}
Thank You.
I have unsubscribed from the event handlers and killed the process before exiting the function. However, the data is still received in OutputDataReceived
and ErrorDataReceived
, even when the program has already exited the GetYTTitle()
function. How can I stop receiving these interminable data in the event handlers?
antonio is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.