raising cross thread events in a DLL without a GUI in C# - c#

I've written a DLL that does a bunch of stuff. One of the things it does is to search through a lot of incoming messages for a specific message, clean up the message, and raise an event when the message is found, and pass the data via the EventArgs.
Currently the DLL is working but the routine that searches for the message is slowing everything down and making the system slow to respond because there is so much data to go through.
I would like to move this searching to it's own thread, and once the message is found have it raise an event on the main thread and pass the message data to the main thread. I know how to make a thread to do the work, but I do not know how to make the thread raise the event on the main thread and pass the data to it. Could someone tell me how to do this, or point to an example of it?
I've tried creating a delegate and triggering an event, which works but when I try to pass the data I get a cross thread exception.
Some details that may be important. There most likely won't be a GUI at all and will probably remain a console application. Messages will always be coming in and the DLL has to continuously search them. The message the DLL is looking for may come as often as 1 couple times a second or it may be days between the messages.
Update for a real simple project illustrating what I would like to do. This code is rough cause I threw it together to test this out.
If you follow the code you will see that everything runs fine until the line in the CollectData function where:
StatusUpdated(this, null);
is called. At this point it causes the cross thread exception because of the UI thread and the data Collection thread. I know I can fix this by using an invoke on the UI thread, but as mentioned above this will most likely not be used with any sort of GUI (but it should be able to handle it). So the cross thread exception needs to be fixed in the BuildResultsManager class, I think in the function BRMgr_StatusUpdated. How do I get the data (in this case the value of currentVal) to the UI thread without changing any code in the MainWindow class.
You can run this by creating a solution with 2 projects, 1 for the first 2 files as a dll. The second as a wpf project, referencing the dll, and put a textbox named status on the form.
Main Class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace BuildResultsManager
{
/// <summary>
/// Delegate to notify when data has changed
/// </summary>
/// <param name="sender">unused</param>
/// <param name="e">unused</param>
public delegate void StatusUpdatedEventHandler(object sender, EventArgs e);
/// <summary>
/// Connects to the PLC via PVI and reads in all the build results data, conditions it, updates values and reads/store into the database
/// </summary>
public class BuildResultsManager
{
#region events
// Change in The Build Results Manger Status
public event StatusUpdatedEventHandler StatusUpdated;
#endregion
#region Local variables
private Thread collectionThread;
private string statusMessage;
DataCollector dataCollection;
#endregion
#region Properties
/// <summary>
/// Current Status of the Build Results manager
/// </summary>
public String StatusMessage
{
get
{
return statusMessage;
}
private set
{
statusMessage = value;
if (StatusUpdated != null)
StatusUpdated(this, null);
}
}
#endregion
#region Constructors
/// <summary>
/// Default constructor
/// </summary>
public BuildResultsManager()
{
StatusMessage = "successfully initialized";
// start the thread that will collect all the data
dataCollection = new DataCollector();
dataCollection.StatusUpdated += new DCStatusUpdatedEventHandler(BRMgr_StatusUpdated);
collectionThread = new Thread(new ThreadStart(dataCollection.CollectData));
collectionThread.Start();
}
/// <summary>
/// EVent to handle updated status text
/// </summary>
/// <param name="sender">unused</param>
/// <param name="e">unused</param>
void BRMgr_StatusUpdated(object sender, EventArgs e)
{
StatusMessage = dataCollection.currentVal.ToString();
}
#endregion
}
}
The class that will be doing all of the thread work:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Windows.Threading;
using System.Threading;
namespace BuildResultsManager
{
/// <summary>
/// Delegate to notify when data has changed
/// </summary>
/// <param name="sender">unused</param>
/// <param name="e">unused</param>
public delegate void DCStatusUpdatedEventHandler(object sender, EventArgs e);
/// <summary>
/// Handles all of the data collection and conditioning
/// </summary>
class DataCollector
{
#region events
// Change in The Build Results Manger Status
public event DCStatusUpdatedEventHandler StatusUpdated;
#endregion
private const long updateInterval = 1000;
private Stopwatch updateTimer;
public int currentVal;
#region local variables
private bool shouldStop;
#endregion
/// <summary>
/// Default Constructor
/// </summary>
public DataCollector()
{
shouldStop = false;
updateTimer = new Stopwatch();
updateTimer.Start();
}
/// <summary>
/// Main task that listens for new data and collects it when it's available
/// </summary>
public void CollectData()
{
currentVal = 5;
while (!shouldStop && currentVal < 10)
{
if(updateTimer.ElapsedMilliseconds > updateInterval)
{
currentVal++;
if (StatusUpdated != null)
{
StatusUpdated(this, null);
}
//reset the timer
updateTimer.Restart();
}
}
}
/// <summary>
/// Asks the thread to stop
/// </summary>
public void RequestStop()
{
shouldStop = true;
}
}
}
Code behind for the wpf project:
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
#region Local variables
private string BRMgrStatus;
private BuildResultsManager.BuildResultsManager BRMgr;
#endregion
public MainWindow()
{
InitializeComponent();
// create an instance of the build manager
BRMgr = new BuildResultsManager.BuildResultsManager();
if(BRMgr != null)
{
status.Text = BRMgr.StatusMessage;
BRMgr.StatusUpdated += new StatusUpdatedEventHandler(BRMgr_StatusUpdated);
}
}
/// <summary>
/// EVent to handle updated status text
/// </summary>
/// <param name="sender">unused</param>
/// <param name="e">unused</param>
void BRMgr_StatusUpdated(object sender, EventArgs e)
{
BuildResultsManager.BuildResultsManager brm;
brm = (BuildResultsManager.BuildResultsManager)sender;
status.Text = brm.StatusMessage;
}
}

If you don't use a GUI there's no need to execute things on the same thread, just protect non-thread-safe resources with a locking mechanism (lock, mutex, etc) to avoid concurrent access and you're good.

Related

How do I create an interactive Powershell instance from C#?

I have a Powershell script that requires user interaction. I can call powershell.exe from C# using System.Diagnostics.Process and pass the scripts path as a parameter but I would like the script to be an embedded resource of the project. I tried creating a Runspace (see below) and running the script but because the script requires user interaction I receive an exception.
var assembly = Assembly.GetExecutingAssembly();
var resourceName = "mynamespace.myscriptfile.ps1";
string result = "";
using (Stream stream = assembly.GetManifestResourceStream(resourceName))
using (StreamReader reader = new StreamReader(stream))
{
result = reader.ReadToEnd();
Console.WriteLine(result);
}
//Create Powershell Runspace
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
// Create pipeline and add commands
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(result);
// Execute Script
Collection<PSObject> results = new Collection<PSObject>();
try
{
results = pipeline.Invoke();
}
catch (Exception ex)
{
results.Add(new PSObject((object)ex.Message));
}
runspace.Close();
Console.ReadKey();
Is there a way to either pass the embedded resource to powershell.exe using System.Diagnostics.Process or is there a way to Invoke the script from C# where the user can interact?
UPDATE:
It seems to me that I may be able to use an implementation of the abstract class PSHost along with using the PSHostUserInterface property correctly, I may be able to create a Runspace that takes the PSHost implementation as a parameter to use the native Powershell console. I have been trying to test the idea but I'm not quite sure how to implement the abstract class.
Below is a sample of code that I obtained from Microsoft. I am confused with a couple of things. If it matters I will be creating the Runspace in a console application with a namespace called: WebRequirements in the Program class.
private Host01 program; (Would Host01 be Program?)
PSHostUserInterface (Is this where I would dictate that I want to use a native Powershell host and if so how would I do that?)
internal class MyHost : PSHost
{
///
/// A reference to the PSHost implementation.
///
private Host01 program;
/// <summary>
/// The culture information of the thread that created
/// this object.
/// </summary>
private CultureInfo originalCultureInfo =
System.Threading.Thread.CurrentThread.CurrentCulture;
/// <summary>
/// The UI culture information of the thread that created
/// this object.
/// </summary>
private CultureInfo originalUICultureInfo =
System.Threading.Thread.CurrentThread.CurrentUICulture;
/// <summary>
/// The identifier of this PSHost implementation.
/// </summary>
private Guid myId = Guid.NewGuid();
/// <summary>
/// Initializes a new instance of the MyHost class. Keep
/// a reference to the host application object so that it
/// can be informed of when to exit.
/// </summary>
/// <param name="program">
/// A reference to the host application object.
/// </param>
public MyHost(Host01 program)
{
this.program = program;
}
/// <summary>
/// Return the culture information to use. This implementation
/// returns a snapshot of the culture information of the thread
/// that created this object.
/// </summary>
public override System.Globalization.CultureInfo CurrentCulture
{
get { return this.originalCultureInfo; }
}
/// <summary>
/// Return the UI culture information to use. This implementation
/// returns a snapshot of the UI culture information of the thread
/// that created this object.
/// </summary>
public override System.Globalization.CultureInfo CurrentUICulture
{
get { return this.originalUICultureInfo; }
}
/// <summary>
/// This implementation always returns the GUID allocated at
/// instantiation time.
/// </summary>
public override Guid InstanceId
{
get { return this.myId; }
}
/// <summary>
/// Return a string that contains the name of the host implementation.
/// Keep in mind that this string may be used by script writers to
/// identify when your host is being used.
/// </summary>
public override string Name
{
get { return "MySampleConsoleHostImplementation"; }
}
/// <summary>
/// This sample does not implement a PSHostUserInterface component so
/// this property simply returns null.
/// </summary>
public override PSHostUserInterface UI
{
get { return null; }
}
/// <summary>
/// Return the version object for this application. Typically this
/// should match the version resource in the application.
/// </summary>
public override Version Version
{
get { return new Version(1, 0, 0, 0); }
}
/// <summary>
/// Not implemented by this example class. The call fails with
/// a NotImplementedException exception.
/// </summary>
public override void EnterNestedPrompt()
{
throw new NotImplementedException(
"The method or operation is not implemented.");
}
/// <summary>
/// Not implemented by this example class. The call fails
/// with a NotImplementedException exception.
/// </summary>
public override void ExitNestedPrompt()
{
throw new NotImplementedException(
"The method or operation is not implemented.");
}
/// <summary>
/// This API is called before an external application process is
/// started. Typically it is used to save state so the parent can
/// restore state that has been modified by a child process (after
/// the child exits). In this example, this functionality is not
/// needed so the method returns nothing.
/// </summary>
public override void NotifyBeginApplication()
{
return;
}
/// <summary>
/// This API is called after an external application process finishes.
/// Typically it is used to restore state that a child process may
/// have altered. In this example, this functionality is not
/// needed so the method returns nothing.
/// </summary>
public override void NotifyEndApplication()
{
return;
}
/// <summary>
/// Indicate to the host application that exit has
/// been requested. Pass the exit code that the host
/// application should use when exiting the process.
/// </summary>
/// <param name="exitCode">The exit code to use.</param>
public override void SetShouldExit(int exitCode)
{
this.program.ShouldExit = true;
this.program.ExitCode = exitCode;
}
}

How to make a call-back timer thread-safe if the code-execution time is not static or always known?

I'm newer to coding, as a warning not an excuse. I currently have a quick timer class 'wrapper' I use. While most of the time I've used it, it worked as expected, I now have an issue.
The code the timer calls back does not always have a set or even accurate estimate of how long it will take to execute that chunk of code start to finish. This leaves me with abnormally long timer update intervals to account for it, or, alternatively stop the timer, and start it again each time it 'ticks' to prevent over-lap.
I've found the first method unacceptable in my case. The second one sounded perfect, but when I tried it it slowed down the code a lot and could have easily ticked much more often after I reviewed it. I'm not sure why it slows it down so much.
Should I look at another way at doing this, besides timers, like some kind of manual control over the flow of events? This is for a simple game-update loop class. Here is said class in full below.
public class TimedUpdater<T>
{
#region Public Delegates/Events
/// <summary>
/// An event that is raised repeatedly at the Interval[in milliseconds] for this Instance.
/// </summary>
public event EventHandler<T> OnUpdate;
#endregion
#region Fields, Private Properties
private Timer Timer { get; }
private TimerCallback Callback { get; }
private T State { get; }
#endregion
#region Constructors, Destructors
/// <summary>
/// Initializes a new instance of the <see cref="TimedUpdater{T}" /> class.
/// </summary>
/// <param name="state">The state object to use for updating data.</param>
/// <param name="name">The unique name representing this instance.</param>
/// <param name="updateRateMs">The rate the the <code>OnUpdate</code> event is raised in milliseconds.</param>
public TimedUpdater(T state, string name, int updateRateMs)
{
Name = name;
Interval = updateRateMs;
State = state;
Callback += Process;
Timer = new Timer(Callback, State, Timeout.Infinite, Timeout.Infinite);
}
/// <summary>
/// Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage
/// collection.
/// </summary>
~TimedUpdater()
{
Dispose();
}
#endregion
#region Public Properties, Indexers
/// <summary>
/// Gets or sets the interval in milliseconds.
/// </summary>
/// <value>The interval in milaseconds.</value>
public int Interval { get; set; }
/// <summary>
/// States if the updater is enabled.
/// </summary>
public bool IsEnabled { get; private set; }
/// <summary>
/// Gets the unique name that represents this instance.
/// </summary>
/// <value>The name.</value>
public string Name { get; }
#endregion
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Disable();
Timer.Dispose();
}
/// <summary>
/// Enables the updater.
/// </summary>
public void Enable()
{
Timer.Change(Interval, Interval);
IsEnabled = true;
}
/// <summary>
/// Disables the updater.
/// </summary>
public void Disable()
{
Timer.Change(int.MaxValue, Interval);
IsEnabled = false;
}
/// <summary>
/// Processes the specified object casted to the type.
/// </summary>
/// <param name="e">The e.</param>
protected virtual void Process(object e)
{
OnUpdate?.Invoke(this, (T) e);
}
}

Force USB Thumb Drive to Mount Before Continue

I am writing an updater program on in C# using Visual Studio 2008 on Windows 7. I would like the user to insert a USB thumb drive and if the program finds the drive and updates on the drive then it automatically copies them over. I desire to check only once at startup and then execute a program that is unaware of the updates (updates really need to happen with the program shutdown).
My issue is that the update program is being run before the thumb drive is being mounted so the computer detects no thumb drive and no updates and moves on prematurely. I want to have everything running as fast as possible but I need to force any thumb drives to mount before detection. Everything must be automatic with no input from the user.
Is this possible in c#?
Edit with more detail:
I currently run a batch file at startup (actually as the Windows 7 shell, but I'm not sure that makes a difference). The batch file runs the update check then the actual program. If the user had the USB drive stuck in at boot then I would like the updater to look at the drive and copy over any new files.
The current coded looks like:
DriveInfo[] ListDrives = DriveInfo.GetDrives();
foreach (DriveInfo Drive in ListDrives)
{
if(Drive.DriveType == DriveType.Removable)
{
// double check it's valid and copy over stuff
}
}
but it currently finds no drives at boot. If I run it later then everything is fine. I am assuming that since I run the updater so early it just hasn't had a chance to mount, but I don't just want to wait N seconds if I don't have to because under normal circumstances that's just dead time.
If I can do this check easy up from it is much simpler than having to continually monitor for an event and then shut everything down and do an update.
I would suggest a solution like the following one:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading;
/// <summary>
/// Represents our program class which contains the entry point of our application.
/// </summary>
public class Program
{
/// <summary>
/// Represents the entry point of our application.
/// </summary>
/// <param name="args">Possibly spcified command line arguments.</param>
public static void Main(string[] args)
{
RemovableDriveWatcher rdw = new RemovableDriveWatcher(); // Create a new instance of the RemoveableDriveWatcher class.
rdw.NewDriveFound += NewDriveFound; // Connect to the "NewDriveFound" event.
rdw.DriveRemoved += DriveRemoved; // Connect to the "DriveRemoved" event.
rdw.Start(); // Start watching.
// Do something here...
Console.ReadLine();
rdw.Stop(); // Stop watching.
}
/// <summary>
/// Is executed when a new drive has been found.
/// </summary>
/// <param name="sender">The sender of this event.</param>
/// <param name="e">The event arguments containing the changed drive.</param>
private static void NewDriveFound(object sender, RemovableDriveWatcherEventArgs e)
{
Console.WriteLine(string.Format("Found a new drive, the name is: {0}", e.ChangedDrive.Name));
}
/// <summary>
/// Is executed when a drive has been removed.
/// </summary>
/// <param name="sender">The sender of this event.</param>
/// <param name="e">The event arguments containing the changed drive.</param>
private static void DriveRemoved(object sender, RemovableDriveWatcherEventArgs e)
{
Console.WriteLine(string.Format("The drive with the name {0} has been removed.", e.ChangedDrive.Name));
}
}
The RemoveableDriveWatcher class looks like this:
/// <summary>
/// Repesents a watcher class for removable drives.
/// </summary>
public class RemovableDriveWatcher
{
/// <summary>
/// Represents the watcher thread which watches for new drives.
/// </summary>
private Thread watcherThread;
/// <summary>
/// Continas all found logical drives of this system.
/// </summary>
private List<DriveInfo> foundDrives;
/// <summary>
/// Initializes a new instance of the <see cref="RemovableDriveWatcher"/> class.
/// </summary>
public RemovableDriveWatcher()
{
this.foundDrives = new List<DriveInfo>();
this.watcherThread = new Thread(new ThreadStart(ScanLogicalDrives));
this.WaitBetweenScansDelay = 1000;
}
/// <summary>
/// Is fired if a new drive has been detected.
/// </summary>
public event EventHandler<RemovableDriveWatcherEventArgs> NewDriveFound;
/// <summary>
/// Is fired if a drive has been removed.
/// </summary>
public event EventHandler<RemovableDriveWatcherEventArgs> DriveRemoved;
/// <summary>
/// Gets or sets the delay in ms between two scans.
/// </summary>
public int WaitBetweenScansDelay
{
get;
set;
}
/// <summary>
/// Starts the watcher.
/// </summary>
public void Start()
{
if (!this.watcherThread.IsAlive)
{
this.watcherThread.Start();
}
}
/// <summary>
/// Stops the watcher.
/// </summary>
public void Stop()
{
if (this.watcherThread.IsAlive)
{
this.watcherThread.Abort();
this.watcherThread.Join();
}
}
/// <summary>
/// Scans for logical drives and fires an event every time a new
/// drive has been found or a drive was removed.
/// </summary>
private void ScanLogicalDrives()
{
DriveInfo[] drives;
do
{
drives = DriveInfo.GetDrives();
// Check for new drives
foreach (DriveInfo drive in drives)
{
if (!(drive.DriveType == DriveType.Removable))
{
continue;
}
if (!drive.IsReady)
{
continue;
}
if (!this.foundDrives.ContainsWithName(drive))
{
this.foundDrives.Add(drive);
if (this.NewDriveFound != null)
{
this.NewDriveFound(this, new RemovableDriveWatcherEventArgs(drives, drive));
}
}
}
// Check for removed drives
for (int i = this.foundDrives.Count - 1; i >= 0; i--)
{
DriveInfo drive = this.foundDrives[i];
if (!drives.ContainsWithName(drive))
{
if (this.DriveRemoved != null)
{
this.DriveRemoved(this, new RemovableDriveWatcherEventArgs(drives, drive));
}
this.foundDrives.RemoveWithName(drive);
}
}
// Sleep
Thread.Sleep(this.WaitBetweenScansDelay);
}
while (true);
}
}
For everything to work you need the RemovableDriveWatcherEventArgs:
/// <summary>
/// Represents the RemovableDriveWatcherEventArgs
/// </summary>
public class RemovableDriveWatcherEventArgs : EventArgs
{
/// <summary>
/// Initializes a new instance of the <see cref="RemovableDriveWatcherEventArgs"/> class.
/// </summary>
/// <param name="allDrives">All currently available logical drives in the system.</param>
/// <param name="changedDrive">The changed drive.</param>
public RemovableDriveWatcherEventArgs(DriveInfo[] allDrives, DriveInfo changedDrive)
{
this.Drives = allDrives;
this.ChangedDrive = changedDrive;
}
/// <summary>
/// Gets the changed logical drive that has either been detected or removed.
/// </summary>
public DriveInfo ChangedDrive { get; private set; }
/// <summary>
/// Gets all currently available logical drives.
/// </summary>
public DriveInfo[] Drives { get; private set; }
}
And of course the Extensions:
/// <summary>
/// Contains extensions used by the RemovableDriveWatcher class.
/// </summary>
public static class RemovableDriveWatcherExtensions
{
/// <summary>
/// Extends the DiveInfo[] by the ContainsWithName method.
/// </summary>
/// <param name="all">The array where we want to find the specified instance.</param>
/// <param name="search">The instance which we want to find in the array.</param>
/// <returns>TRUE if the specified instance was found, FALSE if the specified instance was not found.</returns>
public static bool ContainsWithName(this DriveInfo[] all, DriveInfo search)
{
for (int i = 0; i < all.Length; i++)
{
if (all[i].Name == search.Name)
{
return true;
}
}
return false;
}
/// <summary>
/// Extends the List<DriveInfo> by the ContainsWithName method.
/// </summary>
/// <param name="all">The array where we want to find the specified instance.</param>
/// <param name="search">The instance which we want to find in the list.</param>
/// <returns>TRUE if the specified instance was found, FALSE if the specified instance was not found.</returns>
public static bool ContainsWithName(this List<DriveInfo> all, DriveInfo search)
{
for (int i = 0; i < all.Count; i++)
{
if (all[i].Name == search.Name)
{
return true;
}
}
return false;
}
/// <summary>
/// Extends the List<DriveInfo> by the RemoveWithName method.
/// </summary>
/// <param name="all">The array where we want to removed the specified instance.</param>
/// <param name="search">The instance which we want to remove in the list.</param>
public static void RemoveWithName(this List<DriveInfo> all, DriveInfo search)
{
for (int i = 0; i < all.Count; i++)
{
if (all[i].Name == search.Name)
{
all.RemoveAt(i);
return;
}
}
}
}
I hope this helps a little bit.
You don't give much detail, but it seems likely you could call DriveInfo.GetDrives() which returns an array of type DriveInfo[]
DriveInfo has an IsReady() method. Presumably once you check that the drive is ready, you can look for a well-known file on the USB drive() to verify they have mounted the correct USB
You could poll in a loop till you find what you want, but if you don't find what you want in say 60 seconds, you will need to notify the user that you can't find the USB drive you need.
I do not see a ready check inside of the if statement. According to MSDN:
IsReady indicates whether a drive is ready. For example, it indicates
whether a CD is in a CD drive or whether a removable storage device is
ready for read/write operations. If you do not test whether a drive is
ready, and it is not ready, querying the drive using DriveInfo will
raise an IOException.
Are you checking for an IOException? I do not see an IsReady event so you may have to spinwait or hook into the lower level Windows API to find an event to indicate drive readiness. Here's an idea for the meantime:
try
{
DriveInfo[] ListDrives = DriveInfo.GetDrives();
foreach (DriveInfo Drive in ListDrives)
{
if(!Drive.IsReady)//spin
if(Drive.DriveType == DriveType.Removable)
{
// double check it's valid and copy over stuff
}
}
}
catch(IOException ex)//...
I don't have any way to test this right now. Please let me know how it works out for you or if there's more details I need to be aware of.
However, because you are starting this process on startup there's always the possibility that IsReady will not be sufficient and once again you may have to find something else (Windows API I imagine). I have not discovered any documentation that say's anything to the effect.

I'm not sure if my game is working yet

My friend and I have been working on a game and we have a trace listener set up, here's some of the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
namespace GuiGame {
/// <summary>
/// A type of Trace Listener that sends its output to a ListBox.
/// </summary>
public class ListBoxTraceListener : TraceListener {
private ListBox listBox; // A reference to the listbox that we're writing to.
private string stringToAddToListBox = "";
private const char NEW_LINE = '\n';
/// <summary>
/// Parameterless constructor.
/// Do not want the generic default constructor to be used
/// as there is no way to set the ListBoxTraceListener's data.
/// This replaces the compiler's generic default constructor.
/// Pre: none
/// Post: ALWAYS throws an ArgumentException.
/// </summary>
/// <remarks>NOT TO BE USED!</remarks>
public ListBoxTraceListener() {
throw new ArgumentException("Parameterless constructor invalid.");
} // end ListBoxTraceListener constructor
/// <summary>
/// Constructor with initialising parameters.
/// Pre: the existence of a ListBox on a GUI form.
/// Post: initialised object.
/// </summary>
/// <param name="listBox">The ListBox that we're writing to.</param>
public ListBoxTraceListener(ListBox listBox) {
this.listBox = listBox;
}
/// <summary>
/// Automatically collects the outputs from all Trace.WriteLine statements.
/// Pre: none.
/// Post: the string s is displayed in the listBox.
/// </summary>
/// <param name="s"></param>
public override void WriteLine(string s) {
Write(s + NEW_LINE);
} //end WriteLine
/// <summary>
/// Automatically collects the outputs from all Trace.Write statements.
/// Pre: none.
/// Post: the string s is displayed in the listBox, once we receive a NEW_LINE.
/// </summary>
/// <param name="s"></param>
public override void Write(string s) {
stringToAddToListBox += s;
// If we have one or more complete lines
if (stringToAddToListBox.Contains (NEW_LINE)) {
// Split the string into multiple lines.
// If NEW_LINE is found at the beginning or end of the string,
// then the corresponding array element contains an empty string.
string[] lines = stringToAddToListBox.Split(NEW_LINE);
// Add all the lines to the listbox, except for the last one.
// When stringToAddToListBox has a new-line at the end,
// the last element in lines[] will be an empty string.
int highestLineNumber = lines.Length - 1;
for (int i = 0; i < highestLineNumber; i++) {
AddToListBox(lines[i]);
}
// Reset stringToAddToListBox to what remains. (May be an empty string).
stringToAddToListBox = lines[highestLineNumber];
}
} // end Write
/// <summary>
/// Adds a complete output-line to the ListBox.
/// Pre: none.
/// Post: the string listBoxLine is displayed in the listBox .
/// </summary>
/// <param name="listBoxLine"></param>
private void AddToListBox(string listBoxLine) {
Debug.Assert(listBox != null, "listBox != null");
listBox.Items.Add(listBoxLine);
} // end AddToListBox
}
}
At this stage we are just trying to use the trace listener to output some text on in the ListBox so we know it is working, so we have an event handler setup:
private void RollDiceButton_Click(object sender, EventArgs e)
{
}
We haven't been able to get any output from the trace listener. The Add method as the trace listener is not set up for that. Can anyone provide some suggestions please? I think maybe we are doing something really stupid and obvious that we have missed.
The most probable cause of your issue is that your application is single threaded (as most simple Windows applications are). This means that although you are sending messages to the listview to append a new element to the list, the message is not yet handled just because your original handler hasn't returned yet (the RollDiceButton_Click).
To work this around, you should force the list to refresh itself from within the current handler:
private void AddToListBox(string listBoxLine) {
Debug.Assert(listBox != null, "listBox != null");
listBox.Items.Add(listBoxLine);
// this would help?
listBox.Refresh();
} // end
If this doesn't help, try temporarily switching to unconditional processing of all pending events with
private void AddToListBox(string listBoxLine) {
Debug.Assert(listBox != null, "listBox != null");
listBox.Items.Add(listBoxLine);
// this would help?
Application.DoEvents();
} // end
and report back.

Alternative to ObservableDictionary that focuses on performance

The c# app that I'm working on uses an ObservableDictionary. The performance on this is not nearly fast enough to accommodate it's functionality. The ObservableDictionary is very rapidly being interacted with (Removing, Adding, and Updating elements) and has to sort every single time a change is made. Is there an alternative I can use to ObservableDictionary that would focus on performance and still be able to sort rapidly?
It's very simple to write your own that does not cause a rebinding each time an add / update or delete is done. We wrote our own because of this very reason. Essentially what we do is to disable the notification that a change has been made until all objects in the collection have been processed, and then we generate the notification. It looks something like this. As you can see, we use MvvmLight as our MVVM framework library. This will improve performance tremendously.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using FS.Mes.Client.Mvvm.MvvmTools.MvvmLight;
namespace FS.Mes.Client.Mvvm.MvvmTools
{
/// <summary>
/// Our implementation of ObservableCollection. This fixes one significant limitation in the .NET Framework implementation. When items
/// are added or removed from an observable collection, the OnCollectionChanged event is fired for each item. Depending on how the collection
/// is bound, this can cause significant performance issues. This implementation gets around this by suppressing the notification until all
/// items are added or removed. This implementation is also thread safe. Operations against this collection are always done on the thread that
/// owns the collection.
/// </summary>
/// <typeparam name="T">Collection type</typeparam>
public class FsObservableCollection<T> : ObservableCollection<T>
{
#region [Constructor]
/// <summary>
/// Constructor
/// </summary>
public FsObservableCollection()
{
DispatcherHelper.Initialize();
}
#endregion
#region [Public Properties]
/// <summary>
/// Gets or sets a property that determines if we are delaying notifications on updates.
/// </summary>
public bool DelayOnCollectionChangedNotification { get; set; }
#endregion
/// <summary>
/// Add a range of IEnumerable items to the observable collection and optionally delay notification until the operation is complete.
/// </summary>
/// <param name="items"></param>
/// <param name="delayCollectionChangedNotification">Value indicating whether delay notification will be turned on/off</param>
public void AddRange(IEnumerable<T> items, bool delayCollectionChangedNotification = true)
{
if (items == null)
throw new ArgumentNullException("items");
DoDispatchedAction(() =>
{
DelayOnCollectionChangedNotification = delayCollectionChangedNotification;
// Do we have any items to add?
if (items.Any())
{
try
{
foreach (var item in items)
this.Add(item);
}
finally
{
// We're done. Turn delay notification off and call the OnCollectionChanged() method and tell it we had a 'dramatic' change
// in the collection.
DelayOnCollectionChangedNotification = false;
this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
}
});
}
/// <summary>
/// Clear the items in the ObservableCollection and optionally delay notification until the operation is complete.
/// </summary>
public void ClearItems(bool delayCollectionChangedNotification = true)
{
// Do we have anything to remove?
if (!this.Any())
return;
DoDispatchedAction(() =>
{
try
{
DelayOnCollectionChangedNotification = delayCollectionChangedNotification;
this.Clear();
}
finally
{
// We're done. Turn delay notification off and call the OnCollectionChanged() method and tell it we had a 'dramatic' change
// in the collection.
DelayOnCollectionChangedNotification = false;
this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
});
}
/// <summary>
/// Override the virtual OnCollectionChanged() method on the ObservableCollection class.
/// </summary>
/// <param name="e">Event arguments</param>
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
DoDispatchedAction(() =>
{
if (!DelayOnCollectionChangedNotification)
base.OnCollectionChanged(e);
});
}
/// <summary>
/// Makes sure 'action' is executed on the thread that owns the object. Otherwise, things will go boom.
/// </summary>
///<param name="action">The action which should be executed</param>
private static void DoDispatchedAction(Action action)
{
DispatcherHelper.CheckInvokeOnUI(action);
}
}
}

Categories

Resources