代码改变世界

The Async Work In WPF

2012-02-20 10:40  barbarossia  阅读(201)  评论(0编辑  收藏  举报

The implement of async work in wpf.

The source code:

        /// <summary>
/// Executes the work in background to avoid hangs
/// </summary>
/// <param name="work"></param>
protected void WorkInBackground(DoWorkEventHandler work, RunWorkerCompletedEventHandler onCompleted = null)
{
//Getting called from DIS.Presentation.KMT, execute on background worker
if (uiDispatcher != null)
{
using (BackgroundWorker worker = new BackgroundWorker())
{
worker.DoWork += (s, e) =>
{
try
{
Thread.CurrentThread.CurrentUICulture = KmtConstants.CurrentCulture;
Thread.CurrentThread.CurrentCulture = KmtConstants.CurrentCulture;
}
catch (Exception ex)
{
ExceptionHandler.HandleException(ex);
}
work(s, e);
};
if (onCompleted == null)
onCompleted = new RunWorkerCompletedEventHandler((s, e) =>
{
if (e.Result != null)
{
if (!(e.Result is Message))
throw new ApplicationException("Background worker result is invalid.");

Message msg = e.Result as Message;
if (msg != null)
{
Window parent = GetCurrentWindow();
if (parent != null)
MessageBox.Show(parent, msg.Content, msg.Title);
else
MessageBox.Show(msg.Content, msg.Title);
}
}
});
worker.RunWorkerCompleted += onCompleted;
worker.RunWorkerAsync();
}
}
//Getting called from unit test, execute on main thread
else
{
work.Invoke(null, new DoWorkEventArgs(null));
}
}

The usage is:

        /// <summary>
/// Main Window Button Click Event Handler for Get Keys
/// </summary>
public void GetKeys()
{
//Background thread for updating Key State to DB
IsBusy = true;
base.WorkInBackground((s, e) =>
{
string resultMessage = string.Empty;
switch (KmtConstants.PITLocation)
{
case InstallerType.OEMCorp:
resultMessage = GetKeysByOem();
break;
case InstallerType.TPICorp:
resultMessage = GetKeysByTpi();
break;
case InstallerType.FactoryFloor:
resultMessage = GetKeysByFF();
break;
}
e.Result = new Message(MergedResources.Common_Message, resultMessage);
Search();
IsBusy = false;
});
}