将状态消息从一个类发送到我的Main方法

本文关键字:我的 方法 Main 一个 消息 状态 | 更新日期: 2023-09-27 18:00:03

我有一个类,它有一个很长的foreach循环,可能需要一分钟甚至更长的时间来运行,这取决于我正在解析、插入、更新等记录的数量。。

所以我有一个类是这样的:

public class FileManeger
{
   public bool ParseFile()
   {
       // ....stuff
       foreach(DataRow row in Rows)
       {
            // stuff
       }
   }
}

然后在我的program.cs main method:

FileManager manager = new FileManager();
Console.Writeline("Parsing started...");
manager.ParseFile();
Console.Writeline("Parsing Finished.");

所以我在想,也许在这两条消息之间,我可以再显示一些反馈,例如,在foreach循环中,每经过50行,就放一个计数器打印控制台消息,如"从6500行解析第1至50行"、"从6500行分析第51至100行"、等。

所以我想我需要写一些event,但我对事件没有经验,有人能帮我写吗?

将状态消息从一个类发送到我的Main方法

以下是一些入门知识。您可以使用代理。

public class FileManeger
{
   public Action<string> Trace {get;set;}
   public bool ParseFile()
   {
       // ....stuff
       foreach(DataRow row in Rows)
       {
            // stuff
            this.Trace("Send a message like this");
       }
   }
}

然后在您的主中

FileManager manager = new FileManager();
Console.Writeline("Parsing started...");
manager.Trace = (msg)=>Console.WriteLine(msg);
new Thread(()=>{manager.ParseFile();}).Start();
//    Console.Writeline("Parsing Finished."); let the file parser emit this message

如果你只是想向控制台添加更多消息,那么你可以这样做:

   public bool ParseFile()
   {
       // ....stuff
       int i = 1;
       int count = Rows.Count();
       foreach(DataRow row in Rows)
       {
            Console.WriteLine("parsing row " + i + " from " + count + " rows");
            ++i;
            // stuff
       }
   }

当然,如果你想只为大约每50个元素添加一条消息,那么就把Console.WriteLine部分改为:

if (i%50 == 1) Console.WriteLine("parsing rows " + i + "-" + i+49 + " from " + count + " rows");

但我强烈建议您查看BackgroundWorkers和/或Threads