我试图理解一些代码。它是一个打印日志数据的小程序。它是通过使用由 DataTable 填充的 DataGridView 创建一个表单来完成的。表单类还具有刷新功能(RefreshPresentation)。BusinessLogic 类执行更新 DataTable 和调用表单中的刷新函数的实际工作。所以我非常了解它的功能,但不知道为什么程序的结构是这样的。
- 为什么 businessLogic.DoWork 作为线程而不是普通的方法调用运行?
- 有人可以为我解释一下 RefreshPresentation 功能吗?(BeginInvoke 和委托)
- 将 MainForm 作为参数传递给 BusinessLogic 是一个好主意/做法吗?
这是应用程序的主要入口点。
public class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}
这是表格的相关部分。
public partial class MainForm : Form
{
private BusinessLogic businessLogic;
private DataTable viewDataTable;
public MainForm()
{
InitializeComponent();
businessLogic = new BusinessLogic(this);
Thread t = new Thread(new ThreadStart(businessLogic.DoWork));
t.Start();
}
public delegate void RefreshPresentationDelegate(DataTable dataTable);
public void RefreshPresentation(DataTable dataTable)
{
if (this.InvokeRequired)
{
this.BeginInvoke(new RefreshPresentationDelegate(RefreshPresentation), new object[] { dataTable });
return;
}
...
这就是业务逻辑。
internal class BusinessLogic
{
private MainForm form;
private Logging.DAL.Logger loggerDAL;
private int lastId;
internal DataTable DataTable { get; private set; }
internal bool IsRunning { get; set; }
public BusinessLogic(MainForm form)
{
this.form = form;
this.loggerDAL = new Logging.DAL.Logger();
this.IsRunning = true;
DataTable = new DataTable();
}
public void DoWork()
{
while (this.IsRunning)
{
// Get new log messages.
if (DataTable.Rows.Count > 0)
this.lastId = (int)DataTable.Rows[DataTable.Rows.Count - 1]["Id"];
this.DataTable = loggerDAL.GetLogMessagesSinceLastQuery(lastId);
// Callback to GUI for update.
form.RefreshPresentation(this.DataTable);
// Wait for next refresh.
Thread.Sleep(1000);
}
}
}