I have to process some records. For reasons that are unnecessary to mention, I can not loop through these records at the UI layer. The client wants to be able to simply call the middle tier using a function call, have the middle tier loop through and process the records. The problem is they want the middle tier to report back a status after each record is processed. How would I design that. For what it's worth, this is c# in .net.
A setup similar to this should work. It's untested/uncompiled so consider it pseudo-code. Also, it should ideally be asynchronous, but this will give you a starting point as an example of how to communicate changes back to the UI through eventing without the UI being aware of any "looping".
Event plumbing:
public class MyEventArgs : EventArgs
{
//add properties you want to send to the UI here.
}
public delegate void ProcessedEventHandler(object sender, MyEventArgs e);
Middle tier raises events.
public class MiddleTier
{
public event ProcessedEventHandler RecordProcessed;
//NOTE it would be best to make a tweak to do this asynchronously
//such that all records can be processed at the same time instead
//of processing them sequentially. if the method were async, you
//could do all of this without the method itself blocking.
public void Process()
{
//this loop/processing should ideally be asynchronous
foreach(var thing in whatever)
{
//process thing
//make event args
var args = new MyEventArgs(); //fill out properties
//raise event
OnProcessed(args);
}
private void OnProcessed(MyEventArgs args)
{
//follow this pattern for thread safety
var p = RecordProcessed;
if(p != null)
p(this, args);
}
}
}
Then in your UI layer:
//in some UI function
var mt = new MiddleTier();
//handle event
mt.RecordProcessed +=
(s, args) =>
{
//update UI
};
//kick things off
mt.Process();
You don't mention what technology your UI will be but assuming it is an application, you want the processing to happen on a separate thread so as to allow your UI to update.
I would look at the backgroundworker component as a starting point. It facilitates a progresschanged event you can use to notify your UI of how it getting on. Similar can be achieved using asynchronous framework.
Related
I am fetching data from a database and binding it to 3 different combo boxes simultaneously based on the parent comboBox value. Following is the example, I have three combo boxes named
i. comboBoxBranch
ii. comboBoxClass
iii. comboBoxSection
Value of comboBoxClass is fetched from database on the basis of selected branch, Similarly the value of comboBoxSection is fetched on the basis of selected branch and selected class. So the order of binding is (ComboBoxBranch) then comboBoxClass and then comboBoxSection.
Now in order to acheive this I am using seperate thread to call GetBranches() method to bind data with comboboxBranch in following way.
private void GetBranches() (This is working perfectly fine)
{
if (comboBoxBranches.InvokeRequired)
{
comboBoxBranches.BeginInvoke(((MethodInvoker) delegate
{
comboBoxBranches.DataSource = _schoolManagementSystemServiceClient.GetBranches();
comboBoxBranches.ValueMember = "BranchId";
comboBoxBranches.DisplayMember = "BranchName";
}));
}
Now the problem occurs how should I bind data with other two comboBoxes that are comboxClass and comboBoxSection, Should I use another thread to as I am using for Getbranch Method or there is any other clean method to achieve this. Following is my GetClasses method that I am calling in comboBoxBranches_SelectedValueChanged() event method of comboBoxBranches.
private void comboBoxBranches_SelectedValueChanged(object sender, EventArgs e)
{
Thread thread=new Thread(GetClasses());
thread.start();
}
private void GetClasses()// in this method how should I achieve invoking for multiple controls? What should I do here?
{
if (InvokeRequired)
{
comboBoxBranches.BeginInvoke(((MethodInvoker) delegate
{
Branch branch = comboBoxBranches.SelectedItem as Branch;
}));
comboBoxClasses.BeginInvoke((MethodInvoker) delegate
{
comboBoxClasses.DataSource = _schoolManagementSystemServiceClient.GetClasses(branch.BranchId);
comboBoxClasses.ValueMember = "ClassId";
comboBoxClasses.DisplayMember = "ClassName";
});
}
}
Same method is for comboxBoxSections whose value is based on both ComboBoxBranches and comboBoxClasses? I am new to multi-threading.
Invoking means waiting until the UI thread is idle, then switch to the UI thread and perform some actions. Therefore, the long running task (e.g. querying data from a database) must be performed before invoking takes place.
Today the preferred way to achieve this is to use async/await.
private async void comboBoxBranches_SelectedValueChanged(object sender, EventArgs e)
{
// We are in the UI thread and can access the controls directly.
Branch branch = comboBoxBranches.SelectedItem as Branch;
var classes = await Task.Run(
// This runs in a new thread. At this point the UI is not blocked.
() => _schoolManagementSystemServiceClient.GetClasses(branch.BranchId)
);
// Here the thread joins the UI thread and returns the classes.
// We are in the UI thread again. No need for Invoke.
comboBoxClasses.DataSource = classes;
comboBoxClasses.ValueMember = "ClassId";
comboBoxClasses.DisplayMember = "ClassName";
}
Note the keyword async in the method header. It tells C# to handle this method in a special way. Behind the scenes C# rewrites this method completely to make the magic happen and hides the complexity involved.
To understand how this works, you can imagine that C# puts the lines after the awaited task (the 3 lines with comboBoxClasses) into a callback method.
As explained in Async in depth (Microsoft) you also should rewrite GetClasses to work asynchronously and to return a Task<T> object, instead of starting a new thread here.
var classes = await _schoolManagementSystemServiceClient.GetClassesAsync(branch.BranchId);
See: Asynchronous programming (Microsoft).
I have a WPF application and I am working with the .NET Framework 4.0 and C#. My application consists of an interface with several controls. In particular I have a task that needs to be executed periodically every 10 seconds. In order to execute it I use a System.Windows.Threading.DispatcherTimer. The ViewModel looks like this:
public class WindowViewModel {
protected DispatcherTimer cycle;
public WindowViewModel() {
this.cycle = new DispatcherTimer(DispatcherPriority.Normal,
System.Windows.Application.Current.Dispatcher);
this.cycle.Interval = new TimeSpan(0,0,0,0,10000);
this.cycle.Tick += delegate(object sender, EventArgs e) {
for (int i = 0; i < 20; i++) {
// Doing something
}
};
this.cycle.Start;
}
}
As I said the routine called periodically does something. In particular there is some heavy logic there which causes that routine to take some seconds to execute and complete. Well it is a different thread so I should be ok and the interface is not supposed to freeze.
The problem is that that routine causes the viewmodel to be updated. Several data are updated, and the corresponding View is bound to those data. What happens is that all updated data are refreshed once at a time when the routine completes. I want data to be updated during the thread execution.
In particular inside that routine I have a for cycle. Well at the exit of the cycle everything is updated in the interface. How to achieve this? Where am i doing wrong?
The DispatcherTimer uses the supplied Dispatcher to run the timer callback.
If you take a look at the docs for Dispatcher, there's a clue:
Provides services for managing the queue of work items for a thread.
So, by using the System.Windows.Application.Current.Dispatcher, you're using the Dispatcher that manages "the queue of work items" for the UI thread.
To run your work in the ThreadPool instead, you could either use System.Threading.Timer or use ThreadPool.QueueUserWorkItem in your DispatcherTimer callback.
If you combine this with the following extension method, it becomes easy to marshal any UI specific stuff back to the Dispatcher when you finish your heavy workload:
public static class DispatcherEx
{
public static void InvokeOrExecute(this Dispatcher dispatcher, Action action)
{
if (dispatcher.CheckAccess())
{
action();
}
else
{
dispatcher.BeginInvoke(DispatcherPriority.Normal,
action);
}
}
}
then...
this.cycle.Tick += delegate(object sender, EventArgs e) {
ThreadPool.QueueUserWorkItem(_ => {
for (int i = 0; i < 20; i++) {
// Doing something heavy
System.Windows.Application.Current.Dispatcher.InvokeOrExecute(() => {
//update the UI on the UI thread.
});
}
});
};
I have a class to launch background operations in a WinForms application. I need to write this background worker since my requisites are using .NET 1.1, so I cannot use BackgroundWorker, that is only available from .NET 2.0
This class get a delegate and execute it in a thread. I want the main thread to respond to events.
I also want to indicate that the operation is running setting the application cursor to Cursors.WaitCursor.
What do you think about current implementation? I'm interested in the method WaitTillThreadFinishes(), because I'm not sure about Application.DoEvents(), please read the code and share with me opinions about WaitTillThreadFinishes.
The following code executes the operation:
private object ExecuteOperation (Delegate target, params object[] parameters)
{
mTargetDelegate = target;
mTargetParameters = parameters;
mTargetThread = new Thread(new ThreadStart(ThreadProc));
mTargetThread.Name = mTargetDelegate.Method.Name;
mOperationFinished = false;
// start threaded operation
mTargetThread.Start();
// perform active waiting
WaitTillThreadFinishes();
return mTargetResult;
}
The following code is executed in a thread, simply call the delegate, and wrap exceptions:
protected virtual void ThreadProc()
{
try
{
mTargetResult = mTargetDelegate.DynamicInvoke(mTargetParameters);
}
catch (ThreadAbortException) { }
catch (Exception ex)
{
//manage exceptions here ...
}
finally
{
mOperationFinished = true;
}
}
And this is the code performs an active waiting. I'm interested on share with you. Any better option? Any pain calling Application.DoEvents() massively?
private void WaitTillThreadFinishes ()
{
// Active wait to respond to events with a WaitCursor
while (!mOperationFinished)
{
// sleep to avoid CPU usage
System.Threading.Thread.Sleep(100);
Application.DoEvents();
Cursor.Current = Cursors.WaitCursor;
}
Cursor.Current = Cursors.Default;
}
Thanks in advance.
Please let me know if i understood your question correctly.
Why dont you use an event to notify the UI that the worker finished his job?
This way, the UI doen't get blocked by the worker, and you avoid busy waiting.
Sample Implementation
public class MyBackgroundWorker
{
// Fields
private Delegate _target;
private object[] _arguments;
// Events
public event EventHandler RunWorkerStarted;
public event EventHandler<RunWorkerCompletedEventArgs> RunWorkerCompleted;
// Event Invocators
public void InvokeRunWorkerStarted()
{
var handler = RunWorkerStarted;
if (handler != null) handler(this, new EventArgs());
}
public void InvokeRunWorkerCompleted(object result)
{
var handler = RunWorkerCompleted;
if (handler != null) handler(this, new RunWorkerCompletedEventArgs(result));
}
public void RunWorkerAsync(Delegate target, params object[] arguments)
{
_target = target;
_arguments = arguments;
new Thread(DoWork).Start(arguments);
}
// Helper method to run the target delegate
private void DoWork(object obj)
{
_target.DynamicInvoke(_arguments);
// Retrieve the target delegate's result and invoke the RunWorkerCompleted event with it (for simplicity, I'm sending null)
InvokeRunWorkerCompleted(null);
}
}
internal class RunWorkerCompletedEventArgs : EventArgs
{
public RunWorkerCompletedEventArgs(object result)
{
Result = result;
}
public object Result { get; set; }
}
Usage
In the UI you can use it this way:
private void button1_Click(object sender, EventArgs e)
{
var worker = new MyBackgroundWorker();
worker.RunWorkerStarted += worker_RunWorkerStarted;
worker.RunWorkerCompleted += worker_Completed;
worker.RunWorkerAsync(new MethodInvoker(SomeLengthyOperation), null);
}
void worker_RunWorkerStarted(object sender, EventArgs e)
{
}
void worker_Completed(object sender, EventArgs e)
{
MessageBox.Show("Worker completed");
}
private void SomeLengthyOperation()
{
Thread.Sleep(5000);
}
Final Notes
Remember to Invoke() in the event handlers to access the UI thread correctly. You can also modify the worker so this is done in a safe way.
There isn't much support in 1.1 for doing this, but I'll tell you what I'd do (sorry, no code at this time).
As for the asynchronous operation, I'd use the APM to kick off and complete the asynchronous method. This is fully supported in 1.1, so no worries there.
The idea is that in the UI, you store some indication that work is being done (a boolean field, for example) and (optionally) a Timer used to "wake up" the UI on a regular basis to check on the current status of the background work and indicate this to the user.
You would set the boolean to indicate you are working in the background, call BeginInvoke() on your delegate (using the overload that takes a callback search for "Executing a Callback Method When an Asynchronous Call Completes
"), and start the Timer. When the user attempts to use the UI, you would optionally check the boolean and cancel the operation, thus preventing the user from doing something harmful while you are waiting. When the timer Ticks, you can check the status of your asynchronous method by, say, a shared field that the method writes updates to and the UI reads. For example, a double which the UI uses to update a progress bar.
Once the callback fires, you clean up your asynchronous mess (i.e., call EndInvoke, and handle any exceptions thrown, etc), turn off the Timer and reset your boolean running indication field.
By using this method, you can keep the UI completely responsive (and partially usable, depending on your overall design), can set up a mechanism to abort the background worker (through the use of another field, the reverse of the boolean mentioned earlier, and inform the user of the status of the operation.
There is occasionally a case for kicking off a thread and waiting for its return, if you are doing other things in the meantime, but in this case, with the code you have shown, it is meaningless.
If you want the threadProc to allow for events to be processed, then call doevents in that, which will free up the CPU briefly, allowing for processing.
Unless you have a particular reason for needing to thread processes, you should not do it. Getting it right - as Ian Boyd has said - is difficult, and the more you need to interact with it the harder it is. If you can run fire-and-forget threads, that is the easiest.
Ideally you start the asynchronous operation and leave your form alone (aside from maybe using the Cursors.AppStarting cursor).
When your threaded operation completes, it then needs to fire some sort of BackgroundOperationComplete event. This is where your would call from your asynchronous delegate code:
form.Invoke(BackgroundOperationComplete);
The form's BackgroundOperationComplete method is where you can handle the fact that the background operation is complete:
void BackgroundOperationComplete()
{
this.Cursor = Cursors.DefaultCursor;
lblAnswer.Text = "The thread is done";
}
If all else fails, keep the operation synchronous, and use an IProgressDialog. (brief conceptual pseudo-code from memory):
void DoStuff()
{
IProgressDialog pd = new ProgressDialog();
pd.SetTitle = "Calculating Widgets";
pd.StartTimer(PDTIMER_RESET, NULL)
pd.StartProgressDialog(this.Handle, NULL, PROGDLG_MODAL | PROGDLG_NOTIME | PROGDLG_NOPROGRESSBAR | PROGDLG_NOCANCEL, NULL);
try
{
pd.SetLine(1, "Please wait while the widgets are frobbed");
DoTheThingThatDoesTheSynchronousStuff();
}
finally
{
pd.StopProgressDialog();
}
pd = null;
}
I'm working on this Silverlight 3.0 Project that is completely filled with Async Calls to a Web Service. At the Main Page it fetches some needed data in order for the application to work correctly using 3 Async Calls. Right now the application does not disable any controls while executing those calls meaning a user can interact with it without that needed data. I need to disable the whole grid and only after all 3 Async calls are finished then and only then enable the grid.
What's the best practice for doing this.
These are my calls:
client.GetAllAsync();
client.GetAllCompleted += new EventHandler<GetAllCompletedEventArgs>(client_GetAllCompleted);
client.GetActualAsync();
client.GetActualCompleted += new EventHandler<GetActualCompletedEventArgs>(client_GetActualCompleted);
client.GetSomeAsync();
client.GetSomeCompleted += new EventHandler<GetSomeCompletedEventArgs>(client_GetSomeCompleted);
Seems lot a lot of work just to queue some user interactivity.
I typically provide an application-wide interface:
public interface IAppGlobalState
{
void BeginAsync();
void EndAsync();
}
In the implementation, I'll do this:
public partial class MainShell : UserControl, IAppGlobalState
{
private int _queue;
private object _mutex = new Object();
public void BeginASync()
{
Monitor.Enter(_mutex);
if (_queue++ == 0)
{
VisualStateManager.GoToState(this, "BusyState", true);
}
Monitor.Exit(_mutex);
}
public void EndAsync()
{
Monitor.Enter(_mutex);
if (--_queue == 0)
{
VisualStateManager.GoToState(this, "IdleState", true);
}
Monitor.Exit(_mutex);
}
}
Of course if you have heavy multi-threading then you'll use Interlocked on those but most of the time you'll be invoking it from the same thread. Then, you simply do:
GlobalState.BeginAsync();
client.FirstAsyncCall();
GlobalState.BeginAsync();
client.FirstAsyncCall();
And then on the return, just:
GlobalState.EndAsync();
If you have nested calls, no problem, this method unwinds them.
Make a unit of work item in your silverlight
This UOW raises an event when finished
Bind that event to your GUI code
Use signaling or a simple counter in your unit of work to raise the 'finished' event.
I am developing an application in C# using National Instruments Daqmx for performing measurements on certain hardware.
My setup consists of several detectors from which I have to get data during a set period of time, all the while updating my UI with this data.
public class APD : IDevice
{
// Some members and properties go here, removed for clarity.
public event EventHandler ErrorOccurred;
public event EventHandler NewCountsAvailable;
// Constructor
public APD(
string __sBoardID,
string __sPulseGenCtr,
string __sPulseGenTimeBase,
string __sPulseGenTrigger,
string __sAPDTTLCounter,
string __sAPDInputLine)
{
// Removed for clarity.
}
private void APDReadCallback(IAsyncResult __iaresResult)
{
try
{
if (this.m_daqtskRunningTask == __iaresResult.AsyncState)
{
// Get back the values read.
UInt32[] _ui32Values = this.m_rdrCountReader.EndReadMultiSampleUInt32(__iaresResult);
// Do some processing here!
if (NewCountsAvailable != null)
{
NewCountsAvailable(this, new EventArgs());
}
// Read again only if we did not yet read all pixels.
if (this.m_dTotalCountsRead != this.m_iPixelsToRead)
{
this.m_rdrCountReader.BeginReadMultiSampleUInt32(-1, this.m_acllbckCallback, this.m_daqtskAPDCount);
}
else
{
// Removed for clarity.
}
}
}
catch (DaqException exception)
{
// Removed for clarity.
}
}
private void SetupAPDCountAndTiming(double __dBinTimeMilisec, int __iSteps)
{
// Do some things to prepare hardware.
}
public void StartAPDAcquisition(double __dBinTimeMilisec, int __iSteps)
{
this.m_bIsDone = false;
// Prepare all necessary tasks.
this.SetupAPDCountAndTiming(__dBinTimeMilisec, __iSteps);
// Removed for clarity.
// Begin reading asynchronously on the task. We always read all available counts.
this.m_rdrCountReader.BeginReadMultiSampleUInt32(-1, this.m_acllbckCallback, this.m_daqtskAPDCount);
}
public void Stop()
{
// Removed for clarity.
}
}
The object representing the detector basically calls a BeginXXX operation with a callback that holds the EndXXX en also fires an event indicating data available.
I have up to 4 of these detector objects as members of my UI form. I call the Start() method on all of them in sequence to start my measurement. This works and the NewCountsAvailable event fires for all four of them.
Due to the nature of my implementation, the BeginXXX method is called on the UI thread and the Callback and the Event are also on this UI thread. Therefore I cannot use some kind of while loop inside my UI thread to constantly update my UI with the new data because the events constantly fire (I tried this). I also do not want to use some kind of UpdateUI() method in each of the four NewCountsAvailable eventhandlers since this will load my system too much.
Since I am new to threaded programming in C# I am now stuck;
1) What is the "proper" way to handle a situation like this?
2) Is my implementation of the detector object sound? Should I call the Start() methods on these four detector objects from yet another thread?
3) Could I use a timer to update my UI every few hundred miliseconds, irrespective of what the 4 detector objects are doing?
I really have no clue!
I'd use a simple deferred update system.
1) Worker threads signal "data ready" by raising an event
2) UI thread listens for the event. When it is received, it just sets a "data needs updating" flag and returns, so minimal processing occurs on the event itself.
3) UI thread uses a timer (or sits on Application.Idle events) to check the "data needs updating" flag and, if necessary, update the UI. In many cases, UI only needs to be updated once or twice a second, so this need not burn a lot of CPU time.
This allows the UI to continue running as normal all the time (remaining interactive for the user), but within a short period of some data being ready, it is displayed in the UI.
Additionally, and most importantly for good UI, this approach can be used to allow multiple "data ready" events to fire and be rolled into a single UI update. This means that if 10 pieces of data are completed in close succession, the UI updates once rather than your window flickering for several seconds as the UI redraws (unnecessarily) 10 times.
I would try moving the IDevice monitoring logic to seperate threads for each device. The UI can then poll for values via a timer event, button click or some other UI related event. That way your UI will remain responsive and your threads are doing all the heavy lifting. Here's a basic example of this using a continuous loop. Obviously, this is a brutally simple example.
public partial class Form1 : Form
{
int count;
Thread t = null;
public Form1()
{
InitializeComponent();
}
private void ProcessLogic()
{
//CPU intensive loop, if this were in the main thread
//UI hangs...
while (true)
{
count++;
}
}
private void Form1_Load(object sender, EventArgs e)
{
//Cannot directly call ProcessLogic, hangs UI thread.
//ProcessLogic();
//instead, run it in another thread and poll needed values
//see button1_Click
t = new Thread(ProcessLogic);
t.Start();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
t.Abort();
}
private void button1_Click(object sender, EventArgs e)
{
button1.Text = count.ToString();
}
}
Some updates to reflect the new data you've provided:
Although I have my doubts that your EndXXX methods are happening on the UI thread, I still think you should spawn off the work to a background thread and then update the UI either as events are fired or as needed.
Because you've added a tight while loop in your UI, you need to call Application.DoEvents to allow your other events to be called.
Here's an updated sample that shows results in the UI as they occur:
public class NewCountArgs : EventArgs
{
public NewCountArgs(int count)
{
Count = count;
}
public int Count
{
get; protected set;
}
}
public class ADP
{
public event EventHandler<NewCountArgs> NewCountsAvailable;
private double _interval;
private double _steps;
private Thread _backgroundThread;
public void StartAcquisition(double interval, double steps)
{
_interval = interval;
_steps = steps;
// other setup work
_backgroundThread = new Thread(new ThreadStart(StartBackgroundWork));
_backgroundThread.Start();
}
private void StartBackgroundWork()
{
// setup async calls on this thread
m_rdrCountReader.BeginReadMultiSampleUInt32(-1, Callback, _steps);
}
private void Callback(IAsyncResult result)
{
int counts = 0;
// read counts from result....
// raise event for caller
if (NewCountsAvailable != null)
{
NewCountsAvailable(this, new NewCountArgs(counts));
}
}
}
public class Form1 : Form
{
private ADP _adp1;
private TextBox txtOutput; // shows updates as they occur
delegate void SetCountDelegate(int count);
public Form1()
{
InitializeComponent(); // assume txtOutput initialized here
}
public void btnStart_Click(object sender, EventArgs e)
{
_adp1 = new ADP( .... );
_adp1.NewCountsAvailable += NewCountsAvailable;
_adp1.StartAcquisition(....);
while(!_adp1.IsDone)
{
Thread.Sleep(100);
// your NewCountsAvailable callbacks will queue up
// and will need to be processed
Application.DoEvents();
}
// final work here
}
// this event handler will be called from a background thread
private void NewCountsAvailable(object sender, NewCountArgs newCounts)
{
// don't update the UI here, let a thread-aware method do it
SetNewCounts(newCounts.Count);
}
private void SetNewCounts(int counts)
{
// if the current thread isn't the UI thread
if (txtOutput.IsInvokeRequired)
{
// create a delegate for this method and push it to the UI thread
SetCountDelegate d = new SetCountDelegate(SetNewCounts);
this.Invoke(d, new object[] { counts });
}
else
{
// update the UI
txtOutput.Text += String.Format("{0} - Count Value: {1}", DateTime.Now, counts);
}
}
}
I don't know if I fully understand. What if you update you an object that contains the current data. So the callback don't directly interact with the UI. Then you could update the UI at a fixed rate, e.g. n times per second from another thread. See this post on updating UI from a background thread. I am assuming that you are using Windows Forms and not WPF.
The B* * *dy captcha system decided it was a good idea to lose my answer I spent half an hour typing without so much as a warning or a chance to correct... so here we go again:
public class APD : IDevice
{
// Some members and properties go here, removed for clarity.
public event EventHandler ErrorOccurred;
public event EventHandler NewCountsAvailable;
public UInt32[] BufferedCounts
{
// Get for the _ui32Values returned by the EndReadMultiSampleUInt32()
// after they were appended to a list. BufferdCounts therefore supplies
// all values read during the experiment.
}
public bool IsDone
{
// This gets set when a preset number of counts is read by the hardware or when
// Stop() is called.
}
// Constructor
public APD( some parameters )
{
// Removed for clarity.
}
private void APDReadCallback(IAsyncResult __iaresResult)
{
try
{
if (this.m_daqtskRunningTask == __iaresResult.AsyncState)
{
// Get back the values read.
UInt32[] _ui32Values = this.m_rdrCountReader.EndReadMultiSampleUInt32(__iaresResult);
// Do some processing here!
if (NewCountsAvailable != null)
{
NewCountsAvailable(this, new EventArgs());
}
// Read again only if we did not yet read all pixels.
if (this.m_dTotalCountsRead != this.m_iPixelsToRead)
{
this.m_rdrCountReader.BeginReadMultiSampleUInt32(-1, this.m_acllbckCallback, this.m_daqtskAPDCount);
}
else
{
// Removed for clarity.
}
}
}
catch (DaqException exception)
{
// Removed for clarity.
}
}
private void SetupAPDCountAndTiming(double __dBinTimeMilisec, int __iSteps)
{
// Do some things to prepare hardware.
}
public void StartAPDAcquisition(double __dBinTimeMilisec, int __iSteps)
{
this.m_bIsDone = false;
// Prepare all necessary tasks.
this.SetupAPDCountAndTiming(__dBinTimeMilisec, __iSteps);
// Removed for clarity.
// Begin reading asynchronously on the task. We always read all available counts.
this.m_rdrCountReader.BeginReadMultiSampleUInt32(-1, this.m_acllbckCallback, this.m_daqtskAPDCount);
}
public void Stop()
{
// Removed for clarity.
}
}
Note I added some things I mistakenly left out in the original post.
Now on my form I have code like this;
public partial class Form1 : Form
{
private APD m_APD1;
private APD m_APD2;
private APD m_APD3;
private APD m_APD4;
private DataDocument m_Document;
public Form1()
{
InitializeComponent();
}
private void Button1_Click()
{
this.m_APD1 = new APD( ... ); // times four for all APD's
this.m_APD1.NewCountsAvailable += new EventHandler(m_APD1_NewCountsAvailable); // times 4 again...
this.m_APD1.StartAPDAcquisition( ... );
this.m_APD2.StartAPDAcquisition( ... );
this.m_APD3.StartAPDAcquisition( ... );
this.m_APD4.StartAPDAcquisition( ... );
while (!this.m_APD1.IsDone) // Actually I have to check all 4
{
Thread.Sleep(200);
UpdateUI();
}
// Some more code after the measurement is done.
}
private void m_APD1_NewCountsAvailable(object sender, EventArgs e)
{
this.m_document.Append(this.m_APD1.BufferedCounts);
}
private void UpdateUI()
{
// use the data contained in this.m_Document to fill the UI.
}
}
phew, I hope I dod not forget anything yping this a second time (that'll teach me not copying it before hitting Post).
What I see running this code is that;
1) The APD object works as advertised, it measures.
2) The NewCountsAvailable events fire and their handlers get executed
3) APD.StartAPDAcquisition() is called on the UI thread. Thus also BeginXXX is called on this thread. Therefore, by design, the callback is also on this thread and obviously also the NewCountsAvailable eventhandlers run on the UI thread. The only thing that is not on the UI thread is waiting for the hardware to return values to the BeginXXX EndXXX pair of calls.
4) Because the NewCountsAvailable events fire quite a lot, the while loop I intended to use for updating the UI does not run. Typically it runs once in the beginning and then somehow gets interupted by the eventhandlers that need to process. I do not fully understand this though, but it does not work...
I was thinking to solve this by getting rid of the while loop and putting a Forms.Timer on the form where UpdateUI() would be called from the Tick eventhandler. However, I do not know if this would be deemed "best practice". I also do not know if all these eventhandlers will eventually bring the UI thread to a crawl, I might need to add a few more of these APD objects in the future. Also UpdateUI() might contain some heavier code for calculating an image based on the values in m_Document. So the tick eventhandler might also be a resource drain in the timer approach. In case I use this solution I would also need to have a "Done" event in my APD class to notify when each APD finishes.
Should I perhaps not be working with events for notifying that new counts are available but instead work with some kind of "on demand" reading of APD.BufferedCounts and put the whole thing in yet another thread? I really haven't a clue...
I basically need a clean, lightweight solution that scales well should I add yet more APD's :)