The class library should notify the UI project of a change that it can react to and draw the correct UI.
There are a number of aproaches from a method that the UI layer passes to the project B (callbacks) to events the UI layer can subscribe to.
Below is an example with events. See here for more details on raising custom events.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
var projectB = new ProjectB();
projectB.OnUpdateStatus += projectB_OnUpdateStatus;
projectB.Run();
}
private void projectB_OnUpdateStatus(string message)
{
MessageBox.Show(message);
}
}
public class ProjectB
{
public delegate void StatusUpdateHandler(string message);
public event StatusUpdateHandler OnUpdateStatus;
public void Run()
{
OnUpdateStatus("Updated");
}
}
From you comemnts you have mention that you have huge methods inside the business, and need to display some information on the GUI while the business method is not finished yet the processing.
That become all about threads. With the example I have given above it will work however the UI may not update as the currect thread is too busy doing the work. The UI may even lock up while the background task happens.
If you use just mulitpule threads and the aprach above you will find the issue that you cannot update the UI on another thread.
The background worker thread gets around this issue by doing the work on a 2nd thread but the events fire back to the main UI thread. This keeps the UI respoisive and updated.
public partial class Form1 : Form
{
private BackgroundWorker _backgroundfWorker;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
_backgroundfWorker = new BackgroundWorker();
_backgroundfWorker.ProgressChanged += OnUpdateStatus;
_backgroundfWorker.DoWork += backgroundWorker1_DoWork;
_backgroundfWorker.WorkerReportsProgress = true;
_backgroundfWorker.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
var b = new ProjectB();
b.OnUpdateStatus += ProjectBOnUpdateStatus;
b.Run();
}
private void ProjectBOnUpdateStatus(string message)
{
_backgroundfWorker.ReportProgress(0, message);
}
private void OnUpdateStatus(object sender,ProgressChangedEventArgs progressChangedEventArgs)
{
MessageBox.Show(progressChangedEventArgs.UserState.ToString());
}
}