Reputation: 719
I have a method that runs for a very long time and writes to log files. It's set up like this
public class PSOHelper
{
public PSOHelper(string[] params)
{
//set up params here
}
public async void RunApp(string runType)
{
//long running application that writes to a text file
}
}
Then in the main program I call this method like so:
public async Task<bool> PreparePSOAndRunPSO()
{
string[] params;
//code to fetch the parameters
PSOHelper psoH = new PSOHelper (params)
try
{
await Task.Run(() =>
{
psoH.RunApp(RunConfig.RunMode);
});
return true;
}
catch( Exception ex)
{
Helper.log.Error("exception starting PSO", ex);
return false;
}
}
Now, in my Main method I want to call PreparePSOAndRunPSO and then, in a while loop read from the log that is being written to in RunApp until PreparePSOAndRunPSO finishes. What is the right way for me to do this?
Upvotes: 0
Views: 679
Reputation: 1815
One thing is to change your async void RunApp(string runType)
method to async Task RunApp(string runType)
.
Now something like this should work.
public async Task<bool> PreparePSOAndRunPSO()
{
string[] params;
//code to fetch the parameters
PSOHelper psoH = new PSOHelper (params)
try
{
var task = psoH.RunApp(RunConfig.RunMode); //no need to use Task.Run considering the method returns a task.
while (!task.IsCompleted)
{
/* open stream as readonly, read the log, close the stream */
/* if the log isn't to big, you can read to end so you close the stream faster and then parse the entire log on each iteration. If the log is big, you'd need to read it line by line and parse each line */
/* maybe do a await Task.Delay(100); if you have any race conditions */
}
return true;
}
catch( Exception ex)
{
Helper.log.Error("exception starting PSO", ex);
return false;
}
}
Upvotes: 1