== Actions ==
Definition
Action example1 =
(int x) => Console.WriteLine("Write {0}", x);
Action 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:
* [[http://www.albahari.com/threading/part2.aspx#_Rich_Client_Applications|Threading (Part 2): Rich Client Applications and Thread Affinity]]
== Example ==
///----------------------------------------------------------------------------------------
///
/// Close the popup menu.
///
///----------------------------------------------------------------------------------------
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 = this.CloseDelegate();
this.Dispatcher.BeginInvoke(action);
}
///----------------------------------------------------------------------------------------
///
/// Close method deletegate, used by cross thread dispatcher.
///
///
///----------------------------------------------------------------------------------------
private Action CloseDelegate()
{
return delegate()
{
popmnuFitting.IsOpen = false;
m_TimerForDisplay.Enabled = false;
};
}
== Resources ==
* [[http://dotnetperls.com/action|DotNetPerls: Action]]
* [[http://msdn.microsoft.com/en-us/library/018hxwa8.aspx|MSDN: Action of Delete]]
* [[http://stackoverflow.com/questions/371054/uses-of-action-delegate-in-c|StackOverflow: Use of Action Delete in C#]]
* [[http://weblogs.asp.net/cschittko/archive/2008/05/14/wpf-ui-update-from-background-threads.aspx|WPF UI Update from Background Threads]]