0

我有一个运行很长时间并写入日志文件的方法。它是这样设置的

      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
        }
      }

然后在主程序中我这样调用这个方法:

 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;

        }
    }

现在,在我的 Main 方法中,我想调用 PreparePSOAndRunPSO,然后在 while 循环中从正在写入 RunApp 的日志中读取,直到 PreparePSOAndRunPSO 完成。我这样做的正确方法是什么?

4

1 回答 1

1

一件事是将您的async void RunApp(string runType)方法更改为async Task RunApp(string runType).

现在这样的事情应该可以工作了。

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;

    }
}
于 2015-08-13T18:03:17.550 回答