Is System.Diagnostics.EventLog leaking memory? - c#

When I run the following code :
static void Main(string[] args)
{
if (!System.Diagnostics.EventLog.SourceExists("eventSource"))
{
System.Diagnostics.EventLog.CreateEventSource("eventSource", "");
}
System.Diagnostics.EventLog eventLog = new System.Diagnostics.EventLog();
eventLog.Source = "eventSource";
eventLog.Log = "";
for (int i = 0; i < 10000; i++)
{
Thread.Sleep(100);
eventLog.WriteEntry("test", EventLogEntryType.Information);
//I also tried the static method, the program still leaks
//System.Diagnostics.EventLog.WriteEntry("eventSource", "test", EventLogEntryType.Information);
}
Console.ReadKey();
}
The memory usage starts around 1MB, but rise up very quickly and doesn't stop. Why ?

The code I'm using to install windows service with a designated event log:
[RunInstaller(true)]
public partial class SampleServiceInstaller : System.Configuration.Install.Installer
{
private string SampleServiceName = string.Empty;
private string SampleLogName = string.Empty;
public SampleServiceInstaller()
{
this.SampleServiceName = "SampleService";
this.SampleLogName = this.SampleServiceName + "Log";
ServiceProcessInstaller serviceProcessInstaller = new ServiceProcessInstaller();
serviceProcessInstaller.Password = null;
serviceProcessInstaller.Username = null;
serviceProcessInstaller.Account = ServiceAccount.LocalSystem;
ServiceInstaller serviceInstaller = new ServiceInstaller();
//This must be identical to the WindowsService.ServiceBase name
// set in the constructor of WindowsService.cs
serviceInstaller.ServiceName = this.SampleServiceName;
serviceInstaller.DisplayName = this.SampleServiceName;
serviceInstaller.StartType = ServiceStartMode.Automatic;
serviceInstaller.Description = "Sample Windows Service";
// kill the default event log installer
serviceInstaller.Installers.Clear();
// Create Event Source and Event Log    
// This recreates the log every time the service is reinstaled (old messages are lost)
if (EventLog.SourceExists(this.SampleServiceName)) EventLog.DeleteEventSource(this.SampleServiceName);
System.Diagnostics.EventLogInstaller logInstaller = new System.Diagnostics.EventLogInstaller();
logInstaller.Source = this.SampleServiceName; // use same as ServiceName
logInstaller.Log = this.SampleLogName; //can't be the same as service name
// Add all installers
this.Installers.AddRange(new Installer[] {
   serviceProcessInstaller, serviceInstaller, logInstaller
});
}
public override void Install(System.Collections.IDictionary savedState)
{
base.Install(savedState);
}
protected override void OnBeforeUninstall(System.Collections.IDictionary savedState)
{
base.OnBeforeUninstall(savedState);
}
service code:
public partial class SampleService : ServiceBase
{
/// <summary>
/// Designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Event log for the service
/// </summary>
EventLog serviceLog;
/// <summary>
/// Public Constructor for WindowsService.
/// - Initialization code here.
/// </summary>
public SampleService()
{
InitializeComponent();
}
/// <summary>
/// The Main Thread: list of services to run.
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[] { new SampleService() };
ServiceBase.Run(ServicesToRun);
}
/// <summary>
/// Startup code
/// </summary>
/// <param name="args"></param>
protected override void OnStart(string[] args)
{
base.OnStart(args);
//
// run your own start code here
//
serviceLog.WriteEntry("My service started", EventLogEntryType.Information, 0);
}
/// <summary>
/// Stop code
/// </summary>
protected override void OnStop()
{
//
// run your own stop code here
//
serviceLog.WriteEntry("My service stopped", EventLogEntryType.Information, 0);
base.OnStop();
}
/// <summary>
/// Cleanup code
/// </summary>
/// <param name="disposing"></param>
protected override void Dispose(bool disposing)
{
//
// do disposing here
//
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
/// <summary>
/// Pause code
/// </summary>
protected override void OnPause()
{
base.OnPause();
//
// code to run if service pauses
//
}
/// <summary>
/// Continue code
/// </summary>
protected override void OnContinue()
{
base.OnContinue();
//
// code tu run when service continues after being paused
//
}
/// <summary>
/// Called when the System is shutting down
/// - when special handling
/// of code that deals with a system shutdown, such
/// as saving special data before shutdown is needed.
/// </summary>
protected override void OnShutdown()
{
//
// code tu run when system is shut down
//
base.OnShutdown();
}
/// <summary>
/// If sending a command to the service is needed
/// without the need for Remoting or Sockets,
/// this method is used to do custom methods.
/// int command = 128; //Some Arbitrary number between 128 & 256
/// ServiceController sc = new ServiceController("NameOfService");
/// sc.ExecuteCommand(command);
/// </summary>
/// <param name="command">Arbitrary Integer between 128 & 256</param>
protected override void OnCustomCommand(int command)
{
base.OnCustomCommand(command);
//
// handle custom code here
//
}
/// <summary>
/// Useful for detecting power status changes,
/// such as going into Suspend mode or Low Battery for laptops.
/// </summary>
/// <param name="powerStatus">The Power Broadcast Status
/// (BatteryLow, Suspend, etc.)</param>
protected override bool OnPowerEvent(PowerBroadcastStatus powerStatus)
{
//
// handle power events here
//
return base.OnPowerEvent(powerStatus);
}
/// <summary>
/// To handle a change event
/// from a Terminal Server session.
/// Useful if determining
/// when a user logs in remotely or logs off,
/// or when someone logs into the console is needed.
/// </summary>
/// <param name="changeDescription">The Session Change
/// Event that occured.</param>
protected override void OnSessionChange(SessionChangeDescription changeDescription)
{
//
// handle session change here
//
base.OnSessionChange(changeDescription);
}
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
// first 8 letters should be unique
this.ServiceName = "SampleService";
// if you want to log service event to log registered while installing the service
string newLogName = this.ServiceName + "Log";
string newSourceName = this.ServiceName;
if (!EventLog.SourceExists(newSourceName))
{
EventLog.CreateEventSource(newSourceName, newLogName);
}
serviceLog = new EventLog();
serviceLog.Source = newSourceName;
serviceLog.Log = newLogName;
// Causes log to be disposed when the service is disposed
components.Add(serviceLog);
// Flags set whether or not to handle that specific type of event.
this.CanHandlePowerEvent = true;
this.CanHandleSessionChangeEvent = true;
this.CanPauseAndContinue = true;
this.CanShutdown = true;
this.CanStop = true;
}
}

Related

BLE device with Unity

I am trying to create a game in Unity3D which connects to bluetooth low energy device that supports the heart rate service and collects the HR data. I have created a WPF library that has been tested on a console application to connect to a BLE device and read the data which works perfectly. However, I do not know how to use this in Unity.
I transferred the library to Unity and had to disable it for the editor as the code uses Windows namespaces which are not supported in the editor. My problem now is how do I debug the code in Unity to check if the library code is working when I run the game. I tried wrapping the code for calling the library namespace and the functions from the library in #if NETFX_CORE, #if ENABLE_WINMD_SUPPORT, #if WINDOWS_UWP and many more but, never got any of the debug logs that I wrote.
Is there any possible solution to this?
Any help would be appreciated, thank you!
This is the code for the bluetooth LE connection library:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.Advertisement;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using Windows.Devices.Enumeration;
using Windows.Storage.Streams;
namespace BLEHR
{
/// <summary>
/// Wraps and makes use if the <see cref="BluetoothLeAdvertisementWatcher"/>
/// for easier consumption
///
/// </summary>
public class BLEAdvertisementWatcher
{
#region Private Members
/// <summary>
/// The underlying bluetooth watcher class
/// </summary>
private readonly BluetoothLEAdvertisementWatcher mWatcher;
/// <summary>
/// a list of discovered devices
/// </summary>
private readonly Dictionary<string, BLEDevice> mDiscoveredDevices = new Dictionary<string, BLEDevice>();
/// <summary>
/// The details about Gatt services
/// </summary>
private readonly GattServiceIDs mGattServiceIds;
/// <summary>
/// a thread lock object for this class
/// </summary>
private readonly object mThreadLock = new object();
#endregion
#region Public Properties
/// <summary>
/// indicates is this watcher is listening for advertisements
/// </summary>
public bool Listening => mWatcher.Status == BluetoothLEAdvertisementWatcherStatus.Started;
/// <summary>
/// a list of discovered devices
/// </summary>
public IReadOnlyCollection<BLEDevice> DiscoveredDevices
{
get
{
//Clena up any Timeouts
CleanupTimeouts();
//Practice Thread safety
lock (mThreadLock)
{
//Convert to readonly list
return mDiscoveredDevices.Values.ToList().AsReadOnly();
}
}
}
/// <summary>
/// The timeout in seconds that a device is removed from the <see cref="DiscoveredDevices"/>
/// list if it is not re-advertised within this time
/// </summary>
public int TimeoutRemoval { get; set; } = 20;
public int HRValue { get; set; }
#endregion
#region Constructor
/// <summary>
/// The default constructor
/// </summary>
public BLEAdvertisementWatcher(GattServiceIDs gattIds)
{
//Null guard
mGattServiceIds = gattIds ?? throw new ArgumentNullException(nameof(gattIds));
//Create bluetooth listener
mWatcher = new BluetoothLEAdvertisementWatcher
{
ScanningMode = BluetoothLEScanningMode.Active
};
//Listen out for new advertisements
mWatcher.Received += WatcherAdvertisementReceivedAsync;
//Listen out for when the watcher stops listening
mWatcher.Stopped += (watcher, e) =>
{
//Inform listeners
StoppedListening();
};
}
#endregion
#region Private Methods
/// <summary>
/// Listens out for watcher advertisements
/// </summary>
/// <param name="sender"> The Watcher </param>
/// <param name="args">The Arguments </param>
private async void WatcherAdvertisementReceivedAsync(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args)
{
//cleanup timeouts
CleanupTimeouts();
//Get BLE device info
var device = await GetBLEDeviceAsync(args.BluetoothAddress, args.Timestamp, args.RawSignalStrengthInDBm);
//Null guard
if(device == null)
{
return;
}
//is new discovery?
var newDiscovery = false;
var existingName = default(string);
//Lock your doors
lock (mThreadLock)
{
//Check if this is a new discovery
newDiscovery= !mDiscoveredDevices.ContainsKey(device.DeviceID);
//If this is not new...
if (!newDiscovery)
{
//Store the old name
existingName = mDiscoveredDevices[device.DeviceID].Name;
}
}
//Name changed?
var nameChanged =
//if it already exists
!newDiscovery &&
//And is not a blank name
!string.IsNullOrEmpty(device.Name) &&
//And the name is different
existingName != device.Name;
lock (mThreadLock)
{
//add/update the device in the dictionary
mDiscoveredDevices[device.DeviceID] = device;
}
//Inform listeners
DeviceDiscovered(device);
//if new discovery...
if (newDiscovery)
{
//Inform listeners
NewDeviceDiscovered(device);
}
}
/// <summary>
/// Connects to the BLE device and extracts more information from the
/// <seealso cref="https://learn.microsoft.com/en-us/uwp/api/windows.devices.bluetooth.bluetoothledevice"/>
/// </summary>
/// <param name="address">The BT address of the device to connect to</param>
/// <param name="broadcastTime">The time the broadcast message was received</param>
/// <param name="rssi">The signal strength in dB</param>
/// <returns></returns>
private async Task<BLEDevice> GetBLEDeviceAsync(ulong address, DateTimeOffset broadcastTime, short rssi)
{
//Get bluetooth device info
var device = await BluetoothLEDevice.FromBluetoothAddressAsync(address).AsTask();
//Null guard
if(device == null)
{
return null;
}
//Get GATT services that are available
var gatt = await device.GetGattServicesAsync().AsTask();
//if we have any services..
if(gatt.Status == GattCommunicationStatus.Success)
{
//loop each gatt service
foreach(var service in gatt.Services)
{
//This ID contains the GATT profile assigned number we want!
//TODO: Get more info and connect
var gattProfileId = service.Uuid;
}
}
//Return the new device information
return new BLEDevice
(
//Device ID
deviceID: device.DeviceId,
//Bluetooth address
address: device.BluetoothAddress,
//Device name
name: device.Name,
//Broadcast time
broadcastTime: broadcastTime,
//Signal strength
rssi: rssi,
//Is connected
connected: device.ConnectionStatus== BluetoothConnectionStatus.Connected,
//Can Pair?
canPair: device.DeviceInformation.Pairing.CanPair,
//Is Paired?
isPaired: device.DeviceInformation.Pairing.IsPaired
);
}
/// <summary>
/// Prune any timed out devices that we have not heard off
/// </summary>
private void CleanupTimeouts()
{
lock (mThreadLock)
{
//The date in time that if less than means a device has timed out
var threshold = DateTime.UtcNow - TimeSpan.FromSeconds(TimeoutRemoval);
//any devices that have not sent a new broadcast within the time
mDiscoveredDevices.Where(f => f.Value.BroadcastTime < threshold).ToList().ForEach(device =>
{
//remove device
mDiscoveredDevices.Remove(device.Key);
//Inform listeners
DeviceTimeout(device.Value);
});
}
}
#endregion
#region Public events
/// <summary>
/// Fired when the bluetooth watcher stops listening
/// </summary>
public event Action StoppedListening = () => { };
/// <summary>
/// Fired when the bluetooth watcher start listening
/// </summary>
public event Action StartedListening = () => { };
/// <summary>
/// fired when a new device is discovered
/// </summary>
public event Action<BLEDevice> NewDeviceDiscovered = (device) => {};
/// <summary>
/// fired when a device is discovered
/// </summary>
public event Action<BLEDevice> DeviceDiscovered = (device) => { };
/// <summary>
/// Fired when a device is removed for timing out
/// </summary>
public event Action<BLEDevice> DeviceTimeout = (device) => { };
#endregion
#region Public Methods
/// <summary>
/// Starts listening for advertisements
/// </summary>
public void StartListening()
{
lock (mThreadLock)
{
//if already listening...
if (Listening)
{
//DO nothing more
return;
}
//Start the underlying watcher
mWatcher.Start();
}
//inform listeners
StartedListening();
}
/// <summary>
/// Stops listening for advertisements
/// </summary>
public void StopListening()
{
lock (mThreadLock)
{
//if we are not currently listening
if (!Listening)
{
//Do nothing more
return;
}
//Stop listening
mWatcher.Stop();
//clear any devices
mDiscoveredDevices.Clear();
}
}
/// <summary>
/// Attempts to pair to a BLE device, by ID
/// </summary>
/// <param name="deviceID"> The BLE device ID</param>
/// <returns></returns>
public async Task PairToDeviceAsync(string deviceID)
{
//Get bluetooth device info
var device = await BluetoothLEDevice.FromIdAsync(deviceID).AsTask();
//Null guard
if (device == null)
{
//TODO: localize
throw new ArgumentNullException("");
}
//if we are already paired...
if (device.DeviceInformation.Pairing.IsPaired)
{
//un-pair the device
await device.DeviceInformation.Pairing.UnpairAsync().AsTask();
return;
}
//Try and pair to the device
device.DeviceInformation.Pairing.Custom.PairingRequested += (sender, args) =>
{
//Accept all attempts
args.Accept(); // <-- could enter a pin in here to accept
};
var result = await device.DeviceInformation.Pairing.Custom.PairAsync(DevicePairingKinds.ConfirmOnly).AsTask();
//Get GATT services that are available
var gatt = await device.GetGattServicesAsync().AsTask();
GattDeviceService serviceReq = null;
GattCharacteristic characteristicReq = null;
//if we have any services..
if (gatt.Status == GattCommunicationStatus.Success)
{
//loop each gatt service
foreach (var service in gatt.Services)
{
if (service.Uuid == GattServiceUuids.HeartRate)
{
serviceReq = service;
}
//This ID contains the GATT profile assigned number we want!
//TODO: Get more info and connect
var gattProfileId = service.Uuid;
}
var charResults = await serviceReq.GetCharacteristicsAsync().AsTask();
if(charResults.Status == GattCommunicationStatus.Success)
{
foreach (var chars in charResults.Characteristics)
{
if(chars.Uuid == GattCharacteristicUuids.HeartRateMeasurement)
{
characteristicReq = chars;
}
}
GattCharacteristicProperties properties = characteristicReq.CharacteristicProperties;
if (properties.HasFlag(GattCharacteristicProperties.Read))
{
GattReadResult readVal = await characteristicReq.ReadValueAsync().AsTask();
if(readVal.Status == GattCommunicationStatus.Success)
{
var reader = DataReader.FromBuffer(readVal.Value);
byte[] input = new byte[reader.UnconsumedBufferLength];
reader.ReadBytes(input);
HRValue = BitConverter.ToInt32(input, 0);
}
}
}
}
////Log the result
//if(result.Status == DevicePairingResultStatus.Paired)
//{
// Console.WriteLine("Pairing successful");
//}
//else
//{
// Console.WriteLine($"Pairing failed: {result.Status}");
//}
}
#endregion
}
}
And here is the code I am trying in Unity:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
#if NETFX_CORE
using BLEHR
#endif
public class HRTest : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
#if NETFX_CORE
var watcher = new BLEAdvertisementWatcher(new GattServiceIDs());
Debug.Log("Working?");
#endif
}
// Update is called once per frame
void Update()
{
#if WINDOWS_UWP
Debug.Log("Connecting");
#endif
}
}
Debugging with UWP/.Net-Core-only features in Unity seems like an infeasible workflow to me because of the long edit-compile-run cycles. The Unity Editor runs with .Net-Framework and thus can't directly access .Net-Core features. For non-Unity projects there is the possibility to access UWP-API from .Net-Framework via wrappers provided by Windows. But that doesn't work for Unity because of some Unity-specifics1.
BUT there is the possibility to wrap the UWP-calls in a C++ winrt dll and copy the dll to Unity. This way the UWP-API can be also used inside the Unity Editor (e.g. when pushing the play button). My use case also requires BLE and I uploaded my wrapper in this repo. You're free to use it as a starting point if you want.
One last thing: With .Net version 5 which is also announced for Unity, I guess this should become obsolete as version 5 is said to merge .Net-Framework and .Net-Core.
[1] Much information for this answer came from this blog-post by Mike Taulty.

Restarting an app as administrator that uses mutex

I have an application that uses a mutex to stop multiple instances running at the same time, and to accept command line inputs in to the running instance.
I have a function in the app that asks the user if they want to restart as admin when required. For example the features they have enabled might require admin rights.
The mutex class looks like this:
namespace SingleInstanceClassLibrary
{
/// <summary>
/// Enforces single instance for an application.
/// </summary>
public class SingleInstance : IDisposable
{
private Mutex mutex = null;
private Boolean ownsMutex = false;
private Guid identifier = Guid.Empty;
/// <summary>
/// Enforces single instance for an application.
/// </summary>
/// <param name="identifier">An identifier unique to this application. </param>
public SingleInstance(Guid identifier)
{
this.identifier = identifier;
mutex = new Mutex(true, identifier.ToString(), out ownsMutex);
}
/// <summary>
/// Indicates whether this is the first instance of this application.
/// </summary>
public Boolean IsFirstInstance
{ get { return ownsMutex; } }
/// <summary>
/// Passes the given arguments to the first running instance of the application.
/// </summary>
/// <param name="arguments">The arguments to pass.</param>
/// <returns>Return true if the operation succeded, false otherwise. </returns>
public Boolean PassArgumentsToFirstInstance(String[] arguments)
{
if (IsFirstInstance)
throw new InvalidOperationException("This is the first instance.");
try
{
using (NamedPipeClientStream client = new NamedPipeClientStream(identifier.ToString()))
using (StreamWriter writer = new StreamWriter(client))
{
client.Connect(200);
foreach (String argument in arguments)
writer.WriteLine(argument);
}
return true;
}
catch (TimeoutException)
{ } //Couldn't connect to server
catch (IOException)
{ } //Pipe was broken
return false;
}
/// <summary>
/// Listens for arguments being passed from successive instances of the applicaiton.
/// </summary>
public void ListenForArgumentsFromSuccessiveInstances()
{
if (!IsFirstInstance)
throw new InvalidOperationException("This is not the first instance.");
ThreadPool.QueueUserWorkItem(new WaitCallback(ListenForArguments));
}
/// <summary>
/// Listens for arguments on a named pipe.
/// </summary>
/// <param name="state">State object required by WaitCallback delegate.</param>
private void ListenForArguments(Object state)
{
try
{
using (NamedPipeServerStream server = new NamedPipeServerStream(identifier.ToString()))
using (StreamReader reader = new StreamReader(server))
{
server.WaitForConnection();
List<String> arguments = new List<String>();
while (server.IsConnected)
arguments.Add(reader.ReadLine());
ThreadPool.QueueUserWorkItem(new WaitCallback(CallOnArgumentsReceived), arguments.ToArray());
}
}
catch (IOException)
{ } //Pipe was broken
finally
{
ListenForArguments(null);
}
}
/// <summary>
/// Calls the OnArgumentsReceived method casting the state Object to String[].
/// </summary>
/// <param name="state">The arguments to pass.</param>
private void CallOnArgumentsReceived(Object state)
{
OnArgumentsReceived((String[])state);
}
/// <summary>
/// Event raised when arguments are received from successive instances.
/// </summary>
public event EventHandler<ArgumentsReceivedEventArgs> ArgumentsReceived;
/// <summary>
/// Fires the ArgumentsReceived event.
/// </summary>
/// <param name="arguments">The arguments to pass with the ArgumentsReceivedEventArgs.</param>
private void OnArgumentsReceived(String[] arguments)
{
if (ArgumentsReceived != null)
ArgumentsReceived(this, new ArgumentsReceivedEventArgs() { Args = arguments });
}
#region IDisposable
private Boolean disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (mutex != null && ownsMutex)
{
mutex.ReleaseMutex();
mutex = null;
}
disposed = true;
}
}
~SingleInstance()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
I call it like this:
private static void Main()
{
Guid guid = new Guid("{6EAE2E61-E7EE-42bf-8EBE-BAB890C5410F}");
//SingleInstance ensures only 1 instance of the app runs at one time. If another instance is started
//it will be closed. If the 2nd instance included arguments these will be passed to
//the singleInstance_ArgumentsReceived event for originally running process
using (SingleInstance singleInstance = new SingleInstance(guid))
{
//MessageBox.Show(Environment.GetCommandLineArgs().ToString());
//if (Environment.GetCommandLineArgs().Contains("RunAsAdmin"))
//MessageBox.Show("YES");
if (singleInstance.IsFirstInstance || Environment.GetCommandLineArgs().Contains("RunAsAdmin"))
{
singleInstance.ArgumentsReceived += singleInstance_ArgumentsReceived;
singleInstance.ListenForArgumentsFromSuccessiveInstances();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// Show the system tray icon.
//using (ProcessIcon pi = new ProcessIcon())
using (ProcessIcon pi = new ProcessIcon())
{
//Use to pass instance of ProcessIcon to LyncPresenceSwitcher
lyncPresenceSwitcher.processIcon = pi;
//Pass Lync instance
pi.lync = lyncClientController;
pi.Display();
// Make sure the application runs!
Application.Run();
}
}
else
singleInstance.PassArgumentsToFirstInstance(Environment.GetCommandLineArgs());
}
}
//Process arguments past with app execution
private static void singleInstance_ArgumentsReceived(object sender, ArgumentsReceivedEventArgs e)
{
if (settingsBox == null)
return;
foreach (String arg in e.Args)
{
//if arguments include OpenSettings open SettingsBox
if (arg == "OpenSettings")
{
settingsBox.ShowDialog();
}
if (arg == "RunAsAdmin")
{
//singleInstance.Dispose();
}
}
}
The app checks whether settings require admin access and prompts user to restart as admin when required. To restart the app I run this:
if (!IsRunAsAdmin())
{
// Launch itself as administrator
ProcessStartInfo proc = new ProcessStartInfo();
proc.UseShellExecute = true;
proc.WorkingDirectory = Environment.CurrentDirectory;
proc.FileName = Application.ExecutablePath;
proc.Verb = "runas";
proc.Arguments = "RunAsAdmin";
try
{
Process.Start(proc);
System.Environment.Exit(2);
return true;
}
catch
{
// The user refused the elevation.
// Do nothing and return directly ...
return false;
}
The problem is a new instance starts but is closed because of the mutex. Then when I close the original instance I get this:
So I was thinking I could pass an argument to the running instance to tell it to allow a new one to spawn, then close the original. Trouble is I cant figure out how to make this work.
Any help would be very much appreciated :)
p.s. I am a C# novice
Thanks!
The solution is to simply destroy your mutex prior to restarting your application:
mutex.Dispose();

C# 2.0 Multi-threading with a plug-in architecture

I have a well established console application in c# 2.0 that uses plugin architecture.
As of right now, the program uses basic multi-threading that can run several instances. The threads are created and continue on until the application is stopped.
Each instance can load its own variety of plugins and configured separately.
Plugins are inherited from a base plugin. This system has been working like a charm for years.
The plugins are event driven, they all read various events to see if they are called upon, if not they return and let the next plugin read the events to see if they are called out to fire.
This system has been working for years. However, I would like to further the scope of multi-threading to allow the plugins to listen to the events in an asynchronous fashion rather than synchronous. One of the drawbacks of this setup is that once a plugin fires and does its work, it locks out the instance. When the next event is fired it has to wait for the previous work to be completed. Then it will allow the next process to take place.
What I would like it to do, is execute the plugin and not have to wait for the process to end before moving on to the next process to begin by an event.
I am stuck with .Net 2.0 for the time being, and must find a solution in that framework. I have looked at numerous examples and I can not find one that meets the criteria. One of the problems is that each plugin has its own time that it may take to process, and there is no way to count to track the percentage that the plugin is complete. The plugins will start and ends its process when it is done. Depending on the parameters of the event, and the plugin it can take any range of time to complete.
My question would be what would be the best way to handle multi-threading in this situation where plugins are executed by events. I have looked at pages such as http://msdn.microsoft.com/en-us/library/2e08f6yc(v=vs.80).aspx and I can figure out where I would be able to have an entry point in an event driven plugin architecture.
If anyone has any clue, I would appreciate it. The lack of multi-threading in this manner has been the Achilles' heel for this application for years.
Plugin base: These contain some functions that are triggered by events:
using System;
using VhaBot.Communication;
namespace VhaBot
{
/// <summary>
/// Plugin BaseClass, must be inherited by all plugins
/// </summary>
public abstract class PluginBase : MarshalByRefObject
{
private bool _locked;
private string _name;
private string _internalName;
private int _version;
private string _author;
private string[] _contributors;
private string _description;
private PluginState _defaultState;
private string[] _dependencies;
private Command[] _commands;
/// <summary>
/// Friendly display name of plugin
/// </summary>
/// <example>
/// <code>
/// this.Name = "Message of the Day";
/// </code>
/// </example>
public string Name
{
set
{
if (_locked)
{
throw new Exception();
}
_name = value;
}
get { return _name; }
}
/// <summary>
/// Internal name of the plugin
/// </summary>
/// <example>
/// <code>
/// this.InternalName = "VhMotd";
/// </code>
/// </example>
public string InternalName
{
set
{
if (_locked)
{
throw new Exception();
}
_internalName = value.ToLower();
}
get { return _internalName; }
}
/// <summary>
/// Pluigin Version
/// </summary>
/// <remarks>
/// Versions are stored as integers only. Version 1.0.0 would have a value of 100
/// </remarks>
/// <example>
/// <code>
/// this.Version = 100;
/// </code>
/// </example>
public int Version
{
set
{
if (_locked)
{
throw new Exception();
}
_version = value;
}
get { return _version; }
}
/// <summary>
/// Author of the plugin
/// </summary>
/// <example>
/// <code>
/// this.Author = "Vhab";
/// </code>
/// </example>
public string Author
{
set
{
if (_locked)
{
throw new Exception();
}
_author = value;
}
get { return _author; }
}
/// <summary>
/// List of contributors to the development of the plugin.
/// </summary>
/// <example>
/// <code>
/// this.Contributors = new string[] { "Iriche", "Kilmanagh" };
/// </code>
/// </example>
public string[] Contributors
{
set
{
if (_locked)
{
throw new Exception();
}
_contributors = value;
}
get
{
if (_contributors != null)
{
return _contributors;
}
return new string[0];
}
}
/// <summary>
/// Description of the plugin
/// </summary>
/// <example>
/// <code>
/// this.Description = "Provides an interface to the user to view who is online and/or on the private channel.";
/// </code>
/// </example>
public string Description
{
set
{
if (_locked)
{
throw new Exception();
}
_description = value;
}
get { return _description; }
}
/// <summary>
/// The default <see cref="VhaBot.PluginState" /> of the plugin
/// </summary>
/// <example>
/// <code>
/// this.DefaultState = PluginState.Installed;
/// </code>
/// </example>
/// <seealso cref="VhaBot.PluginState" />
public PluginState DefaultState
{
set
{
if (_locked)
{
throw new Exception();
}
_defaultState = value;
}
get { return _defaultState; }
}
/// <summary>
/// List of other plugins that a plugin is dependent on to function
/// </summary>
/// <remarks>
/// Plugins are referred to using their internal names. See <see cref="VhaBot.PluginBase.InternalName" />
/// </remarks>
/// <example>
/// <code>
/// this.Dependencies = new string[] { "vhItems" };
/// </code>
/// </example>
public string[] Dependencies
{
set
{
if (_locked)
{
throw new Exception();
}
_dependencies = value;
}
get
{
if (_dependencies != null)
{
return _dependencies;
}
return new string[0];
}
}
public Command[] Commands
{
set
{
if (_locked)
{
throw new Exception();
}
_commands = value;
}
get
{
if (_commands != null)
{
return _commands;
}
return new Command[0];
}
}
internal void Init()
{
_locked = true;
}
/// <summary>
/// A plugin has loaded in response to <see cref="VhaBot.ShellModules.Plugins.Load" />
/// </summary>
/// <param name="bot"></param>
/// ///
/// <remarks>Code inside this method will be executed when a plugin is loading</remarks>
public virtual void OnLoad(BotShell bot)
{
}
/// <summary>
/// A plugin has unloaded in response to <see cref="VhaBot.ShellModules.Plugins.Unload" />
/// </summary>
/// <param name="bot"></param>
/// <remarks>Code inside this method will be executed when a plugin is unloading</remarks>
public virtual void OnUnload(BotShell bot)
{
}
/// <summary>
/// A plugin has installed in response to <see cref="VhaBot.ShellModules.Plugins.Install" />
/// </summary>
/// <param name="bot"></param>
public virtual void OnInstall(BotShell bot)
{
}
/// <summary>
/// A plugin as been uninstalled in response to <see cref="VhaBot.ShellModules.Plugins.Uninstall" />
/// </summary>
/// <param name="bot"></param>
public virtual void OnUninstall(BotShell bot)
{
}
/// <summary>
/// A plugin has been upgraded (Unused)
/// </summary>
/// <param name="bot"></param>
/// <param name="version"></param>
/// <remarks>This function is not active</remarks>
public virtual void OnUpgrade(BotShell bot, Int32 version)
{
}
/// <summary>
/// Response to a command
/// </summary>
/// <param name="bot"></param>
/// <param name="e"></param>
public virtual void OnCommand(BotShell bot, CommandArgs e)
{
}
/// <summary>
/// Response to an unauthorized command
/// </summary>
/// <param name="bot"></param>
/// <param name="e"></param>
public virtual void OnUnauthorizedCommand(BotShell bot, CommandArgs e)
{
}
/// <summary>
/// Response to a command help query <see cref="VhaBot.ShellModules.Commands.GetHelp." />
/// </summary>
/// <param name="bot"></param>
/// <param name="command"></param>
/// <returns></returns>
/// <remarks>Code inside this method will be executed when help is requested</remarks>
public virtual string OnHelp(BotShell bot, string command)
{
return null;
}
/// <summary>
/// Response to a custom configuration
/// </summary>
/// <param name="bot"></param>
/// <param name="key"></param>
/// <returns></returns>
public virtual string OnCustomConfiguration(BotShell bot, string key)
{
return null;
}
/// <summary>
/// Response to a plugin message
/// </summary>
/// <param name="bot"></param>
/// <param name="message"></param>
public virtual void OnPluginMessage(BotShell bot, PluginMessage message)
{
}
/// <summary>
/// Response to a bot message
/// </summary>
/// <param name="bot"></param>
/// <param name="message"></param>
public virtual void OnBotMessage(BotShell bot, BotMessage message)
{
}
/// <summary>
/// Returns display name of bot and current version
/// </summary>
/// <returns></returns>
public override string ToString()
{
return Name + " v" + Version;
}
/// <summary>
/// There is no information to document this command
/// </summary>
/// <param name="bot"></param>
/// <param name="args"></param>
public void FireOnCommand(BotShell bot, CommandArgs args)
{
try
{
if (args.Authorized)
OnCommand(bot, args);
else
OnUnauthorizedCommand(bot, args);
}
catch (Exception ex)
{
CommandArgs e = args;
var window = new RichTextWindow(bot);
window.AppendTitle("Error Report");
window.AppendHighlight("Error: ");
window.AppendNormal(ex.Message);
window.AppendLinkEnd();
window.AppendLineBreak();
window.AppendHighlight("Source: ");
window.AppendNormal(ex.Source);
window.AppendLinkEnd();
window.AppendLineBreak();
window.AppendHighlight("Target Site: ");
window.AppendNormal(ex.TargetSite.ToString());
window.AppendLinkEnd();
window.AppendLineBreak();
window.AppendHighlight("Stack Trace:");
window.AppendLineBreak();
window.AppendNormal(ex.StackTrace);
window.AppendLinkEnd();
window.AppendLineBreak();
bot.SendReply(e,
"There has been an error while executing this command »» " +
window.ToString("More Information"));
BotShell.Output("[Plugin Execution Error] " + ex);
}
}
}
}
Events Class:
namespace VhaBot.ShellModules
{
/// <summary>
/// VhaBot Events
/// </summary>
public class Events
{
public event BotStateChangedHandler BotStateChangedEvent;
public event ChannelJoinEventHandler ChannelJoinEvent;
public event UserJoinChannelHandler UserJoinChannelEvent;
public event UserLeaveChannelHandler UserLeaveChannelEvent;
public event UserLogonHandler UserLogonEvent;
public event UserLogoffHandler UserLogoffEvent;
public event PrivateMessageHandler PrivateMessageEvent;
public event PrivateChannelMessageHandler PrivateChannelMessageEvent;
public event ChannelMessageHandler ChannelMessageEvent;
public event MemberAddedHandler MemberAddedEvent;
public event MemberRemovedHandler MemberRemovedEvent;
public event MemberUpdatedHandler MemberUpdatedEvent;
public event AltAddedHandler AltAddedEvent;
public event AltRemovedHandler AltRemovedEvent;
/// <summary>
/// A message was sent to the IRC channel in response to a <see cref="VhaBot.BotShell.SendIrcMessage" /> request
/// </summary>
public event IrcMessageHandler IrcMessageEvent;
public event ConfigurationChangedHandler ConfigurationChangedEvent;
internal void OnBotStateChanged(BotShell bot, BotStateChangedArgs e)
{
if (BotStateChangedEvent != null)
try
{
BotStateChangedEvent(bot, e);
}
catch
{
}
}
internal void OnChannelJoin(BotShell bot, ChannelJoinEventArgs e)
{
if (ChannelJoinEvent != null)
try
{
ChannelJoinEvent(bot, e);
}
catch
{
}
}
internal void OnUserJoinChannel(BotShell bot, UserJoinChannelArgs e)
{
if (UserJoinChannelEvent != null)
try
{
UserJoinChannelEvent(bot, e);
}
catch
{
}
}
internal void OnUserLeaveChannel(BotShell bot, UserLeaveChannelArgs e)
{
if (UserLeaveChannelEvent != null)
try
{
UserLeaveChannelEvent(bot, e);
}
catch
{
}
}
internal void OnUserLogon(BotShell bot, UserLogonArgs e)
{
if (UserLogonEvent != null)
try
{
UserLogonEvent(bot, e);
}
catch
{
}
}
internal void OnUserLogoff(BotShell bot, UserLogoffArgs e)
{
if (UserLogoffEvent != null)
try
{
UserLogoffEvent(bot, e);
}
catch
{
}
}
internal void OnPrivateMessage(BotShell bot, PrivateMessageArgs e)
{
if (PrivateMessageEvent != null)
try
{
PrivateMessageEvent(bot, e);
}
catch
{
}
}
internal void OnPrivateChannelMessage(BotShell bot, PrivateChannelMessageArgs e)
{
if (PrivateChannelMessageEvent != null)
try
{
PrivateChannelMessageEvent(bot, e);
}
catch
{
}
}
internal void OnChannelMessage(BotShell bot, ChannelMessageArgs e)
{
if (ChannelMessageEvent != null)
try
{
ChannelMessageEvent(bot, e);
}
catch
{
}
}
internal void OnMemberAdded(BotShell bot, MemberAddedArgs e)
{
if (MemberAddedEvent != null)
try
{
MemberAddedEvent(bot, e);
}
catch
{
}
}
internal void OnMemberRemoved(BotShell bot, MemberRemovedArgs e)
{
if (MemberRemovedEvent != null)
try
{
MemberRemovedEvent(bot, e);
}
catch
{
}
}
internal void OnMemberUpdated(BotShell bot, MemberUpdatedArgs e)
{
if (MemberUpdatedEvent != null)
try
{
MemberUpdatedEvent(bot, e);
}
catch
{
}
}
internal void OnAltAdded(BotShell bot, AltAddedArgs e)
{
if (AltAddedEvent != null)
try
{
AltAddedEvent(bot, e);
}
catch
{
}
}
internal void OnAltRemoved(BotShell bot, AltRemovedArgs e)
{
if (AltRemovedEvent != null)
try
{
AltRemovedEvent(bot, e);
}
catch
{
}
}
internal void OnConfigurationChanged(BotShell bot, ConfigurationChangedArgs e)
{
if (ConfigurationChangedEvent != null)
try
{
ConfigurationChangedEvent(bot, e);
}
catch
{
}
}
internal void OnIrcMessage(BotShell bot, IrcMessageArgs e)
{
if (IrcMessageEvent != null)
{
IrcMessageEvent(bot, e);
}
try
{
}
catch
{
}
}
}
}
I've got little to go on as your description of the system is a bit vague but I'll give it a shot.
From your description it seems you have some plugin, say
interface IPlugin {
PluginResult ReadAndExecuteEvents(Events e);
// Added asynchronous methods.
IAsyncResult BeginReadAndExecuteEvents(Events e, AsyncCallback cb, Object state);
PluginResult EndReadAndExecuteEvents(IAsyncResult result);
}
with
class PluginResult
{
public Boolean Stop;
// etc.
}
also you don't seem to be using .NET events, but rather some sort of Event class/enumeration.
Your old code seems to be something like:
foreach (var eventList in ReadEvents())
foreach (var plugin in pluginList)
if (plugin.ReadAndExecuteEvents(eventList).Stop)
break;
You can make this asynchronous doing something like:
foreach (var eventList in ReadEvents())
{
// It seems this is what you want, only one event processed at a time by an "instance"? So block here until unlocked.
LockProcess();
var pluginIndex = 0;
AsyncCallback handleResult = null;
handleResult = delegate(IAsyncResult result)
{
if (pluginList[pluginIndex].EndReadAndExecuteEvents(result).Stop)
goto STOP;
pluginIndex += 1;
if (pluginIndex == pluginList.Count)
goto STOP;
Events e = (Events)result.AsyncState;
pluginList[pluginIndex].BeginReadAndExecuteEvents(e, handleResult, e);
return;
STOP:
UnlockProcess();
};
pluginList[0].BeginReadAndExecuteEvents(eventList, handleResult, eventList);
}
So in .NET 2 style you could add some BeginXxx method and in its AsyncCallback do your stuff.
Of course it is up to the actual plugin to do its multithreading/asynchronisity, say if it writes a file by using BeginWrite to a FileStream etc.
I have conveniently ignored exception handling here.
So, to make your whole application use this asynchronisity you can put this code in a BeginRunEvents method, say, following the same "APM" pattern. You can then schedule this to the threadpool if you wish.
If this is not at all what you are looking for please provide some more code examples/info.

Application.Restart() + Single Instance conflict in windows application

Hi Friends,
I have a windows application where i controls single instance.
When this application updates using clickonce, application will restart after applying updates.
The application restarts but fails to continue as, IsFirstInstance = false condition.
But Application.Restart() documentation says it shutdowns running app and creates new instance.
Single instance class is given below:
using System;
using System.Diagnostics;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Ipc;
using System.Threading;
using agent_common_plugin_sdk;
/// <summary>
/// Application Instance Manager
/// </summary>
public static class ApplicationInstanceManager
{
/// <summary>
/// Creates the single instance.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="callback">The callback.</param>
/// <returns></returns>
public static bool CreateSingleInstance(string name, EventHandler<InstanceCallbackEventArgs> callback)
{
EventWaitHandle eventWaitHandle = null;
string eventName = string.Format("{0}-{1}", Environment.MachineName, name);
InstanceProxy.IsFirstInstance = false;
InstanceProxy.CommandLineArgs = Environment.GetCommandLineArgs();
try
{
// Try opening existing wait handle
eventWaitHandle = EventWaitHandle.OpenExisting(eventName);
}
catch(Exception ex)
{
// Got exception = handle wasn't created yet
InstanceProxy.IsFirstInstance = true;
}
if (InstanceProxy.IsFirstInstance)
{
// init handle
eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, eventName);
// register wait handle for this instance (process)
ThreadPool.RegisterWaitForSingleObject(eventWaitHandle, WaitOrTimerCallback, callback, Timeout.Infinite, false);
eventWaitHandle.Close();
// register shared type (used to pass data between processes)
RegisterRemoteType(name);
}
else
{
// pass console arguments to shared object
UpdateRemoteObject(name);
// invoke (signal) wait handle on other process
if (eventWaitHandle != null) eventWaitHandle.Set();
// kill current process
Environment.Exit(0);
}
return InstanceProxy.IsFirstInstance;
}
/// <summary>
/// Updates the remote object.
/// </summary>
/// <param name="uri">The remote URI.</param>
private static void UpdateRemoteObject(string uri)
{
// register net-pipe channel
IpcClientChannel clientChannel = new IpcClientChannel();
ChannelServices.RegisterChannel(clientChannel, true);
// get shared object from other process
InstanceProxy proxy =
Activator.GetObject(typeof(InstanceProxy),
string.Format("ipc://{0}{1}/{1}", Environment.MachineName, uri)) as InstanceProxy;
// pass current command line args to proxy
if (proxy != null)
proxy.SetCommandLineArgs(InstanceProxy.IsFirstInstance, InstanceProxy.CommandLineArgs);
// close current client channel
ChannelServices.UnregisterChannel(clientChannel);
}
/// <summary>
/// Registers the remote type.
/// </summary>
/// <param name="uri">The URI.</param>
private static void RegisterRemoteType(string uri)
{
// register remote channel (net-pipes)
IpcServerChannel serverChannel = new IpcServerChannel(Environment.MachineName + uri);
ChannelServices.RegisterChannel(serverChannel, true);
// register shared type
RemotingConfiguration.RegisterWellKnownServiceType(
typeof(InstanceProxy), uri, WellKnownObjectMode.Singleton);
// close channel, on process exit
Process process = Process.GetCurrentProcess();
process.Exited += delegate { ChannelServices.UnregisterChannel(serverChannel); };
}
/// <summary>
/// Wait Or Timer Callback Handler
/// </summary>
/// <param name="state">The state.</param>
/// <param name="timedOut">if set to <c>true</c> [timed out].</param>
private static void WaitOrTimerCallback(object state, bool timedOut)
{
// cast to event handler
EventHandler<InstanceCallbackEventArgs> callback = state as EventHandler<InstanceCallbackEventArgs>;
if (callback == null) return;
// invoke event handler on other process
callback(state,
new InstanceCallbackEventArgs(InstanceProxy.IsFirstInstance,
InstanceProxy.CommandLineArgs));
}
}
}
here:
try
{
// Try opening existing wait handle
eventWaitHandle = EventWaitHandle.OpenExisting(eventName);
}
catch(Exception ex)
{
// Got exception = handle wasn't created yet
InstanceProxy.IsFirstInstance = true;
}
no exception is being thrown. Hence as you can see in the code, it will exit from Environment.Exit(0).

C# While Loop in Worker Thread for listening command and response

Overview of the problem:
I try to use a thread (while..loop) to listen a command from user. If user send a command, it will assign new value in the global variable which is in the class (LoopingWorkerThread).
I don't understand if I don't put the thread sleep value lower than 10 milliseconds, and I wouldn't get any response (it is in the ListenCommand method) . Look like the global parameter is being overwritten "_CommandReceived" in the method, probably the processor run to fast and ignore the value of the parameter had changed ("_CommandReceived").
Kindly comment if there is any better mechanism. I had lock it in the ListenCommand while loop.
The following are the codes:
public class LoopingWorkerThread
{
/// <summary>
/// Local main thread for LoopingWorkerThread
/// </summary>
private Thread t;
/// <summary>
/// Local parameter to identify the LoopingWorkerThread Is On
/// </summary>
private bool _IsOn;
/// <summary>
/// Local parameter to store command received from user
/// </summary>
private int _CommandReceived;
/// <summary>
/// Local object to use for locking the LoopingWorker Thread
/// </summary>
private object _LockListenCommand = new object();
/// <summary>
/// Properties of LoopingWorker Thread Is On
/// </summary>
public bool IsOn
{
get { return _IsOn; }
set { _IsOn = value; }
}
/// <summary>
/// Property of storing the command received from user
/// </summary>
public int CommandReceived
{
get { return _CommandReceived; }
set { _CommandReceived = value; }
}
/// <summary>
/// Delegate for OnResponse Event Handler
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public delegate void OnResponseHandler(object sender, ResponseArg e);
/// <summary>
/// Event of OnResponse
/// </summary>
public event OnResponseHandler OnResponse;
/// <summary>
/// Constructor of LoopingWorkerThread Class
/// </summary>
public LoopingWorkerThread()
{
_IsOn = false;
}
/// <summary>
/// Method of LoopingWorkerThread Function
/// </summary>
private void ListenCommand()
{
lock (_LockListenCommand)
while (_IsOn)
{
switch (_CommandReceived)
{
case 0:
// Ignore default command
break;
case 1:
FireOnResponse("Received cmd 1, response [Hello One]");
break;
case 2:
FireOnResponse("Received cmd 2, response [Hello Two]");
break;
default:
FireOnResponse("Error. Received unidentified command - " + _CommandReceived.ToString());
break;
}
//Console.WriteLine("ThreadProc: Cmd:[{0}] - Response:{1}", _CommandReceived.ToString(), ReaderResponse);
// Reset or Clear the Command Received
_CommandReceived = 0;
// If the sleep less than 10 millisecond, it always don't catch the
// command received which assigned to 1 or 2. Don't understand, or is there
// any better method.
**Thread.Sleep(10);**
}
}
/// <summary>
/// Function of firing response event back to user
/// </summary>
/// <param name="message"></param>
private void FireOnResponse(string message)
{
ResponseArg myarg = new ResponseArg(message);
if (OnResponse != null)
OnResponse(this, myarg);
}
/// <summary>
/// Method of starting the LoopingWorkerThread
/// </summary>
public void Start()
{
_IsOn = true;
FireOnResponse("Main thread: Started.");
// The constructor for the Thread class requires a ThreadStart
// delegate that represents the method to be executed on the
// thread. C# simplifies the creation of this delegate.
t = new Thread(new ThreadStart(ListenCommand));
// Start ThreadProc. Note that on a uniprocessor, the new
// thread does not get any processor time until the main thread
// is preempted or yields. Uncomment the Thread.Sleep that
// follows t.Start() to see the difference.
t.Start();
//Thread.Sleep(0);
FireOnResponse("Main thread: Call Start().");
}
/// <summary>
/// Method of stopping the LoopingWorkerThread
/// </summary>
public void Stop()
{
_IsOn = false;
t.Join();
//t.Abort();
FireOnResponse("LoopingWorker Thread is stopped.");
}
/// <summary>
/// Method of sending command to the LoopingWorkerThread
/// </summary>
/// <param name="readercmd"></param>
public void SendCommand(int readercmd)
{
_CommandReceived = readercmd;
}
}
Your code works because Thread.Sleep produces the necessary memory barrier required to read _commandReceived correctly. If you remove the Thread.Sleep call then you also remove the implicit memory barrier. Obviously, this is not a good mechanism to rely on though.
More importantly you are going about this the wrong way. What you should be using is the producer-consumer pattern. This is pretty easy with the BlockingCollection class since it blocks the consumer on Take while the queue is empty.
public class Example
{
private BlockingCollection<int> commands = new BlockingCollection<int>();
public Example()
{
var thread = new Thread(Run);
thread.IsBackground = true;
thread.Start();
}
public void SendCommmand(int command)
{
commands.Add(command);
}
private void Run()
{
while (true)
{
int command = commands.Take();
ProcessCommand(command);
}
}
private void ProcessCommand(int command)
{
// Process the command here.
}
}
BlockingCollection is available for 3.5 as part of the Reactive Extensions download.
Try declaring the variable volatile. More about this on http://msdn.microsoft.com/en-us/library/x13ttww7.aspx

Categories