Skip to content

Instantly share code, notes, and snippets.

@savaged
Created August 30, 2018 10:50
Show Gist options
  • Save savaged/d5d0264c519e1978f0bf24cd14c990d9 to your computer and use it in GitHub Desktop.
Save savaged/d5d0264c519e1978f0bf24cd14c990d9 to your computer and use it in GitHub Desktop.
Busy State Manager - WPF helper (mini framework) for managing IsBusy state
// BusyStateManager usings
using System.Collections.Generic;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Messaging;
using Savaged.Info.Desktop.Messages;
// BusyMessage usings
using System;
using System.Runtime.CompilerServices;
using GalaSoft.MvvmLight.Messaging;
namespace Savaged.Info.Desktop.Helpers
{
/// <summary>
/// A Boolean value for busy which should be used in conjunction with
/// the XCeed Toolkit BusyIndicator or similar control. This class is
/// responsible for managing this state which can be problematic if
/// it is just being set in process because different threads can set
/// it prior to other threads completing. A better solution is to have
/// this central static register of running threads, which unregister
/// once complete, then the busy value is only set to true once the
/// register is empty.
/// </summary>
public class BusyStateManager : ObservableObject
{
private IList<string> _registry;
public BusyStateManager()
{
_registry = new List<string>();
Messenger.Default.Register<BusyMessage>(this, OnBusyMessage);
}
public bool IsBusy => _registry.Count > 0;
private void OnBusyMessage(BusyMessage m)
{
if (m.IsBusy)
{
_registry.Add($"{m.CallerType}.{m.CallerMember}");
}
else
{
_registry.Remove($"{m.CallerType}.{m.CallerMember}");
}
RaisePropertyChanged(nameof(IsBusy));
}
}
}
// This can be put in a different file if you like
namespace Savaged.Info.Desktop.Messages
{
/// <summary>
/// Message for updating Busy State, used in conjunction with
/// Savaged.Info.Desktop.Helpers.BusyStateManager
/// </summary>
/// <example>
/// Used in conjunction with Savaged.Info.Desktop.Helpers.BusyStateManager
/// like this:
/// <code>
/// MessengerInstance.Send(new BusyMessage(true, this));
/// await DoSomthingAsync();
/// MessengerInstance.Send(new BusyMessage(false, this));
/// </code>
/// </example>
public class BusyMessage : MessageBase
{
/// <summary>
/// ctor
/// </summary>
/// <param name="isBusy">The state</param>
/// <param name="caller">The calling class</param>
/// <param name="callerMember">The method or property (leave blank because reflection gets this)</param>
public BusyMessage(bool isBusy, object caller, [CallerMemberName] string callerMember = "")
{
IsBusy = isBusy;
CallerType = caller.GetType();
CallerMember = callerMember;
}
public bool IsBusy { get; }
public Type CallerType { get; }
public string CallerMember { get; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment