Thanks to MichealGG for the code. See his response to my question on StackOverflow here: http://stackoverflow.com/questions/508177/implementing-a-nested-asynch-call-stack-scenario-in-net
using System;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
namespace SilverlightTestApp
{
public partial class Page : UserControl
{
public Page()
{
InitializeComponent();
}
private void AsynchDemo()
{
ResultsTextBlock.Text = "";
ResponseWriteLine("BEGIN: AsynchDemo()");
AsyncHelp(
() => SlowDateTime("The time is now: "),
ex => ResultsTextBlock.Text += ex.ToString(),
bla => ResultsTextBlock.Text += bla.ToString()
);
ResponseWriteLine("CALLED: SlowDateTime()");
Action<string> r = ResponseWrite;
for(int x = 0;x<100;x++)
{
AsyncHelp(
() => RandomSleep(x),
ex => ResultsTextBlock.Text += ex.ToString(),
r); //use a delegate instead of a lambda expression
}
ResponseWriteLine("END: RandomSleep() x 100");
}
public string RandomSleep(int input)
{
Random r = new Random();
int t = r.Next(10000);
Thread.Sleep(t);
return input.ToString() + "."; ;
}
public void ResponseWrite<T>(T result)
{
ResultsTextBlock.Text += result.ToString();
}
public void ResponseWriteLine<T>(T result)
{
ResultsTextBlock.Text += result.ToString() + Environment.NewLine;
}
public string SlowDateTime(string text)
{
Thread.Sleep(5000);
return text + DateTimeOffset.Now.ToString();
}
public void AsyncHelp<T>(Func<T> f, Action<Exception> econt, Action<T> cont)
{
var t = new Thread((_) =>
{
try
{
var res = f();
System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => cont(res));
}
catch (Exception ex)
{
System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => econt(ex));
}
});
t.Start();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
AsynchDemo();
}
}
}
2 comments:
Here's a link to instructions on how to embed Silverlight in Blogger:
http://blog.figmentengine.com/2008/10/embedding-silverlight-in-blogger.html
Thanks for sharing this, it will be very useful to me. This is just what the doctor ordered for my current silverlight conversion project!
Post a Comment