Thread problem c#
I have 2 Threads. In my worker thread (not main Thread) I create a picturebox array and sometimes I need to add a new picturebox to the main form, but I don't have access to this form. I read somewhere that I need to use invoke method but I only know how to update one picturebox or a label. I don't know how to do this with this bit of code:
food[x].Location = new Point(100,100);
food[x].Size = new Size(10,10);
food[x].BorderStyle = B开发者_如何学PythonorderStyle.Fixed3D;
food[x].ImageLocation = "food.png";
this.Controls.Add(food[x]);
food[x].BringToFront;
Could anyone help me?
In WinForms, you should only have one UI thread, and only that thread should create or use UI components.
Use a BackgroundWorker
to load the images, if necessary, and leave the PictureBox
creation to the UI thread on the BackgroundWorker
's completion.
Background threads cannot access GUI controls owned by the main thread.
If you want to communicate information to the GUI, the thread must communicate to the main thread, which then manipulates the GUI control.
BackgroundWorker threads provide ways to signal the main thread. See http://www.dotnetperls.com/backgroundworker for example.
If you use WPF i recommend to use SynchronazationContext to save the main thread, all other thread will use this instance of SynchronazationContext to access the main thread (UI). You use it in this manner (Note: i generated a method that do this and all other methods will access this method to update the UI):
SynchronazationContext ctx = null;
void DoSomething()
{
ctx = SynchronazationContext.Current;
Thread t = new Thread(new ThreadStart(ThreadProc));
t.Start();
}
//This method run in separate Threads
void ThreadProc()
{
//Some algorithm here
SendOrPostCallback callBack = new SendOrPostCallback(UpdatePic);
ctx.Post(callBack, String.Format("Put here the pic path");
}
void UpdatePic(string _text)
{
//This method run under the main method
//In this method you should update the pic
}
In .NET 5.0 you can call this complicated functions by mark the method as async and write 'await' when you call the synchronous method - that make the synchronous method as asynchronous method and update the UI with the main thread.
精彩评论