private void UpdateTextBox(string text) { // Create a new SendOrPostCallback delegate to update the text box SendOrPostCallback callback = state => { textBox1.Text = state as string; }; // Post the callback to the UI synchronization context SynchronizationContext.Current.Post(callback, text); } private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e) { // Simulate some work being done Thread.Sleep(5000); // Call the UpdateTextBox method with the message to display UpdateTextBox("Work complete!"); }
private void DoWorkInBackground(Action work, Action onComplete) { // Create a new SendOrPostCallback delegate to run the work method SendOrPostCallback callback = state => { work(); onComplete(); }; // Post the callback to a new threadpool thread ThreadPool.QueueUserWorkItem(callback); } private void DoWork() { // Simulate some work being done Thread.Sleep(5000); } private void WorkComplete() { // Update the UI to show that the work is complete label1.Text = "Work complete!"; } private void Button_Click(object sender, EventArgs e) { // Start the work on a background thread DoWorkInBackground(DoWork, WorkComplete); }In both of these examples, the SendOrPostCallback delegate is used to update the user interface after some work has been done on a background thread. This ensures that the UI remains responsive while the work is being done.