McKelt.com

Remembering Thoughts

 

Recent comments

Authors

Categories


Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2010

WPF UI Thread Dispatcher

A simple implemention for calling asych methods from the UI

 

Examples

 

1.

dispatcher.ExecuteOnMainUIThread(CommandManager.InvalidateRequerySuggested);

 

2.

dispatcher.Execute(() =>
{
SomeLongRunningMethodHere();
});

 

The interface

 
using System;

namespace Mvvm
{
public interface IDispatcher
{
void Execute(Action action);

void ExecuteOnMainUIThread(Action action);
}
}

Synchronous for use in Testing

 
using System;

namespace Mvvm
{
public class SynchronousDispatcher : IDispatcher
{
public void Execute(Action action)
{
action();
}

public void ExecuteOnMainUIThread(Action action)
{
action();
}
}

}

Asynchronous for use by the application at run time

 
using System;

namespace Mvvm
{
using System.Windows;
using System.Windows.Threading;

public class AsynchronousDispatcher : IDispatcher
{
public void Execute(Action action)
{
action.BeginInvoke(CallBack, action);
}

public void ExecuteOnMainUIThread(Action action)
{
Dispatcher dispatcher;

if (Application.Current != null)
{
dispatcher = Application.Current.Dispatcher;
}
else
{
dispatcher = Dispatcher.CurrentDispatcher;
}

dispatcher.Invoke(action);
}

private void CallBack(IAsyncResult result)
{
try
{
((Action)result.AsyncState).EndInvoke(result);
}
catch (Exception ex)
{
// Need to raise the exception on the main thread
ExecuteOnMainUIThread(() =>
{
throw ex;
}
);
}
finally
{
result.AsyncWaitHandle.Close();
}


}
}
}


Categories: .Net
Posted by chris on Wednesday, May 26, 2010 12:15 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Winforms UI cross thread operations

ThreadPool.QueueUserWorkItem(new WaitCallback(LoadUsers));
 
private void LoadUsers(Object stateInfo)
 
    var site = new SPSite(testHarnessSettings.Url);
     var web = site.OpenWeb();
      foreach(SPUser user in web.AllUsers)
      {
       if (usersListBox.InvokeRequired)
       {
             usersListBox.Invoke(new MethodInvoker(delegate { usersListBox.Items.Add((user.LoginName)); }));
       }                                
 
 

 

http://weblogs.asp.net/justin_rogers/articles/126345.aspx 

Categories: .Net
Posted by chris on Friday, February 27, 2009 1:27 PM
Permalink | Comments (0) | Post RSSRSS comment feed