This is an old revision of the document!
Actions
Definition
Action<int> example1 = (int x) => Console.WriteLine("Write {0}", x); Action<int, int> example2 = (x, y) => Console.WriteLine("Write {0} and {1}", x, y); Action example3 = () => Console.WriteLine("Done");
Using Actions to Communicate Between Background Worker and Main Threads
using System.Windows.Threading; // in WindowsBase.dll public partial class MyWindow : Window { public MyWindow() { InitializeComponent(); new Thread (Work).Start(); } void Work() { Thread.Sleep (5000); // Simulate time-consuming task UpdateMessage ("The answer"); } void UpdateMessage (string message) { Action action = () => txtMessage.Text = message; Dispatcher.Invoke (action); } }
Source:
Example
///---------------------------------------------------------------------------------------- /// <summary> /// Close the popup menu. /// </summary> ///---------------------------------------------------------------------------------------- public void Close() { //---------------------------------------------------------------------------- // Deal with cross thread ownership of UI control instance // by invoking an action delegate. In other words, // popupmnu is owned by thread that instantiated it (when Open() was called), // so we cannot close popmnu arbitrarily. We need the help of // the owner thread's Dispatcher to execute the Close() for us. //---------------------------------------------------------------------------- //Action action = () => popmnuReports.IsOpen = false; Action action = CloseDelegate(); Dispatcher.BeginInvoke(action); } ///---------------------------------------------------------------------------------------- /// <summary> /// Close method deletegate, used by cross thread dispatcher. /// </summary> /// <returns></returns> ///---------------------------------------------------------------------------------------- private Action CloseDelegate() { return delegate() { popmnuFitting.IsOpen = false; m_TimerForDisplay.Enabled = false; }; }