Masz rację, to nie jest dobry, aby przejść do kontroli wątków. Formanty WinForm są jednowątkowe, przekazywanie ich do wielu wątków może powodować warunki wyścigu lub złamać twój interfejs użytkownika. Zamiast tego powinieneś udostępnić funkcje wątku interfejsowi użytkownika i pozwolić mu wywołać wątek, gdy interfejs jest dobry i gotowy. Jeśli chcesz, aby wątki w tle wyzwalały zmiany w interfejsie użytkownika, ujawnij wydarzenie tła i zasubskrybuj je z interfejsu użytkownika. Wątek może uruchamiać zdarzenia w dowolnym momencie, a interfejs użytkownika może na nie reagować, gdy jest to możliwe.
Tworzenie tej dwukierunkowej komunikacji między wątkami, która nie blokuje wątku UI, wymaga dużo pracy. Tutaj jest bardzo skrócona przykład przy użyciu klasy BackgroundWorker:
public class MyBackgroundThread : BackgroundWorker
{
public event EventHandler<ClassToPassToUI> IWantTheUIToDoSomething;
public MyStatus TheUIWantsToKnowThis { get { whatever... } }
public void TheUIWantsMeToDoSomething()
{
// Do something...
}
protected override void OnDoWork(DoWorkEventArgs e)
{
// This is called when the thread is started
while (!CancellationPending)
{
// The UI will set IWantTheUIToDoSomething when it is ready to do things.
if ((IWantTheUIToDoSomething != null) && IHaveUIData())
IWantTheUIToDoSomething(this, new ClassToPassToUI(uiData));
}
}
}
public partial class MyUIClass : Form
{
MyBackgroundThread backgroundThread;
delegate void ChangeUICallback(object sender, ClassToPassToUI uiData);
...
public MyUIClass
{
backgroundThread = new MyBackgroundThread();
// Do this when you're ready for requests from background threads:
backgroundThread.IWantTheUIToDoSomething += new EventHandler<ClassToPassToUI>(SomeoneWantsToChangeTheUI);
// This will run MyBackgroundThread.OnDoWork in a background thread:
backgroundThread.RunWorkerAsync();
}
private void UserClickedAButtonOrSomething(object sender, EventArgs e)
{
// Really this should be done in the background thread,
// it is here as an example of calling a background task from the UI.
if (backgroundThread.TheUIWantsToKnowThis == MyStatus.ThreadIsInAStateToHandleUserRequests)
backgroundThread.TheUIWantsMeToDoSomething();
// The UI can change the UI as well, this will not need marshalling.
SomeoneWantsToChangeTheUI(this, new ClassToPassToUI(localData));
}
void SomeoneWantsToChangeTheUI(object sender, ClassToPassToUI uiData)
{
if (InvokeRequired)
{
// A background thread wants to change the UI.
if (iAmInAStateWhereTheUICanBeChanged)
{
var callback = new ChangeUICallback(SomeoneWantsToChangeTheUI);
Invoke(callback, new object[] { sender, uiData });
}
}
else
{
// This is on the UI thread, either because it was called from the UI or was marshalled.
ChangeTheUI(uiData)
}
}
}
zaznaczyć proszę odpowiedź jako zaakceptowana, jeśli rozwiążesz problem. – SandRock