Very simplistic example of Parallel.Foreach – C# – Faster UI

Keywords: WPF Winforms Slow UI C# speed increase

I am a developer by trade and I run into legacy Winform and WPF applications quite a bit.

I went to look for a simplistic Parallel.ForEach Example, and I couldn’t really find one.

In the constructor you will see something like this. Where everything is Synchronous and slow.

Since some of these are SQL calls unless I go the route of using the new SQL Asynchronous features (which would require a bit of real rework). I am going the lazy route:

GetUser();
LoadWeapons();
LoadPlayer();
LoadLastKnownCombatLocation();

First we want to load each into an Action.
var getUser = () => {GetUser()};
var loadWeapons = () => {LoadWeapons()};
var loadPlayer = () => {LoadPlayer()};
var loadLastKnownCombatLocation = () => {LoadLastKnownCombatLocation()};

//Create List (any IEnumerable should work)
var allActions = new List();

//the add can be done in the instantiation using {}’s instead
allActions.Add(getUser);
allActions.Add(loadWeapons);
allActions.Add(loadPlayer);
allActions.Add(loadLastKnownCombatLocation);

Parallel.ForEach(allActions, (e) => e.Invoke());

This is only solid in situations where UI is not dependent on another call first, IE LoadUser() may be needed to LoadPlayer(), You can easily make a parallel for all data pulls then another for all
UI updating.

–Augmented Developer

Categories: Uncategorized

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: