Já bych místo modulu udělat třídu, pro komunikaci s formulářem bych používal události, pro spouštění práce na jiném než hlavním threadu bych použil Task a pro předání řízení zpět na UI/main thread bych použil SynchronizationContext. Kód v C#:
public partial class Form1 : Form
{
private Worker Worker;
public Form1()
{
InitializeComponent();
this.Worker = new Worker();
this.Worker.Completed += Worker_Completed;
}
private void button1_Click(object sender, EventArgs e)
{
Task.Run(() => this.Worker.SomeWork());
}
private void Worker_Completed(object sender, EventArgs e)
{
label1.Text = "Completed at " + DateTime.Now.ToString("HH:mm:ss");
}
}
internal class Worker
{
private SynchronizationContext SynchronizationContext;
public event EventHandler Completed;
public Worker()
{
this.SynchronizationContext = SynchronizationContext.Current;
}
public void SomeWork()
{
//Work
Thread.Sleep(TimeSpan.FromSeconds(2));
this.SynchronizationContext.Post(_ => OnCompleted(), null);
}
private void OnCompleted()
{
var handler = Completed;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
}
Kód ve VB.NET (z converteru, možná to chce trochu poupravit, ve VB.NET nedělám):
Public Partial Class Form1
Inherits Form
Private Worker As Worker
Public Sub New()
InitializeComponent()
Me.Worker = New Worker()
AddHandler Me.Worker.Completed, AddressOf Worker_Completed
End Sub
Private Sub button1_Click(sender As Object, e As EventArgs)
Task.Run(Function() Me.Worker.SomeWork())
End Sub
Private Sub Worker_Completed(sender As Object, e As EventArgs)
label1.Text = "Completed at " & DateTime.Now.ToString("HH:mm:ss")
End Sub
End Class
Friend Class Worker
Private SynchronizationContext As SynchronizationContext
Public Event Completed As EventHandler
Public Sub New()
Me.SynchronizationContext = SynchronizationContext.Current
End Sub
Public Sub SomeWork()
'Work
Thread.Sleep(TimeSpan.FromSeconds(2))
Me.SynchronizationContext.Post(Function(_) OnCompleted(), Nothing)
End Sub
Private Sub OnCompleted()
Dim handler = Completed
RaiseEvent handler(Me, EventArgs.Empty)
End Sub
End Class
|