Thursday, May 13, 2010

CrossThreadAction

Here's another handy class in the spirit of WeakEventHandler. It's useful when you want to run work on a background thread, but wish to provide a callback that will be run on your own (usually UI) thread. Apparently Silverlight users will find this particularly useful, there being no Application.Current.Dispatcher in Silverlight, but as an almost-exclusively WPF user, I use it as helpful shorthand for "call me back on my own thread".

The class:


public class CrossThreadAction<TData> : DependencyObject
{
Action<TData> target;

public CrossThreadAction(Action<TData> target)
{
this.target = target;
}

private void Invoke(TData data)
{
Dispatcher.BeginInvoke(target, data);
}

public static implicit operator Action<TData>(
CrossThreadAction<TData> cta)
{
return cta.Invoke;
}
}


Use it as follows:


private void StartWork()
{
// using a server method with signature
// void DoWork(Action<string> callback);
server.DoWork(new CrossThreadAction<string>(FinishWork));
}

private void FinishWork(string result)
{
textBlock1.Text = result;
}


WPF users may make it slightly less heavy by inheriting from DispatcherObject instead of DependencyObject. Also, beware of storing an instance in an untyped variable; generally it's a good idea to cast it to Action<TData> as soon as you've created it.

Labels: ,

1 Comments:

Anonymous Anonymous said...

iphone 4 unlock
how to unlock iphone 4
unlock iphone 4

http://www.serjtankian.com/news/new-system-down-headline-dates-south-america http://www.esncagliari.it/event/esn-firenze-cagliari
I use Avira anti-virus and evertime I attempt a scan my computer restarts 1/4 of the way through and the scan is never complete.
unlock iphone 4 how to unlock iphone 4

iphone 4 unlock [url=http://unlockiphone44.com]iphone 4 unlock[/url] how to unlock iphone 4 iphone 4 unlock

10:21 PM  

Post a Comment

<< Home