Differences
This shows you the differences between two versions of the page.
Both sides previous revision Previous revision Next revision | Previous revision | ||
swdev:dotnet:actions [2010/11/10 11:01] smayr |
swdev:dotnet:actions [2011/01/26 16:55] (current) smayr [Example] |
||
---|---|---|---|
Line 8: | Line 8: | ||
Action example3 = | Action example3 = | ||
() => Console.WriteLine(" | () => Console.WriteLine(" | ||
+ | </ | ||
+ | |||
+ | == Using Actions to Communicate Between Background Worker and Main Threads == | ||
+ | |||
+ | <code csharp> | ||
+ | using System.Windows.Threading; | ||
+ | |||
+ | public partial class MyWindow : Window | ||
+ | { | ||
+ | public MyWindow() | ||
+ | { | ||
+ | InitializeComponent(); | ||
+ | new Thread (Work).Start(); | ||
+ | } | ||
+ | |||
+ | void Work() | ||
+ | { | ||
+ | Thread.Sleep (5000); | ||
+ | UpdateMessage ("The answer" | ||
+ | } | ||
+ | |||
+ | void UpdateMessage (string message) | ||
+ | { | ||
+ | Action action = () => txtMessage.Text = message; | ||
+ | Dispatcher.Invoke (action); | ||
+ | } | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | Source: | ||
+ | * [[http:// | ||
+ | |||
+ | == Example == | ||
+ | |||
+ | <code csharp> | ||
+ | /// | ||
+ | /// < | ||
+ | /// 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. | ||
+ | // the owner thread' | ||
+ | // | ||
+ | //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 == | == Resources == | ||
Line 13: | Line 81: | ||
* [[http:// | * [[http:// | ||
* [[http:// | * [[http:// | ||
+ | * [[http:// |