Callback to execute when a thread is finished - multithreading

Disclaimer (fully editable/removable)
I've done my homework but to the best of my recognition, I can't see the very thing I'd like to know (which is a bit surprising, so I'm sure that a kind soul will flag me as a duplicate - please accept my apology in advance, haha).
Background and anticipated issue
When I start Outlook, I'm performing an update from CRM Dynamics, which takes a while. So, I decided to put the update in a thread. It works as supposed to but there's a button on the ribbon allowing a user to manually call for an update. Anticipating a frantic user, I realize that someone will click the button before the original update is finished and all kinds of excrement may hit the gas redistributive device.
Suggested solution
In order to avoid that, I've put a private property as follows.
private bool KeepYourPantsOn { get; set; }
As long as the said property is true (which it is set to right before I start the updating thread), all the frantic clicking will be either ignored or treated by a calm and informative
MessageBox.Show("Yes, yes... Updating still... Keep your pants on.");
but as soon as the thread is done, I'd like the property to flip over to false enabling the user to manually update Outlook.
Implementation problem
My hick-up is that I haven't found any OnFinished, WhenDone etc. method to call in order to switch the value of KeepYourPantsOn. Moreover, I haven't really seen any suggested solution on how to resolve that (or, rather - I haven't perceived any solution - I might have seen one without realizing that was it, due to ignorance within the area of threaded programming).

You should be able to just set the bool to false as the last line in your thread (or as the last line before looping back to wait on something, if your thread does that).
Note #Tudor comment regarding volatile - just to be sure, do it.

You can create a backing store for your property to hold the value and use a lock whenever you set or get the value to ensure that no concurrency issue arises.
After that, when you start processing on a separate thread, set the value to true and before exiting the method set the value to false.
On user click just check the value of KeepYourPantsOn property and display the message if it is still true.
class YourClass
{
private static readonly object _syncRoot = new object();
private bool _keepYourPantsOn;
public bool KeepYourPantsOn
{
get
{
lock(_syncRoot)
{
return _keepYourPantsOn;
}
}
set
{
lock(_syncRoot)
{
_keepYourPantsOn = value;
}
}
}
private ThreadMethod()
{
KeepYourPantsOn = true; //signal that the update process is starting...
// perform your logic
KeepYourPantsOn = false; //signal that the update process is finished
}
public ManualUpdate()
{
if(KeepYourPantsOn)
MessageBox.Show("Yes, yes... Updating still... Keep your pants on.");
else
Update();
}
}

Related

Is there a way to tell R# that after I run a a method, certain class variables won't be null

Consider the following code:
public class TestClass
{
public int? NullableInt { get; set; }
private bool DoPreChecks()
{
if(NullableInt == null)
return false;
return true;
}
public bool DoTest()
{
if(!DoPreChecks())
return false;
//Here R# tells me that "nullableInt" may be null
if (NullableInt.Value > 10)
{
// Do something
}
return true;
}
}
R# would be correct to worry that "NullableInt.Value" may be null when I reference it in "DoTest", except that if it was, then "DoPreChecks" would have returned false and that means I would never have gotten to this line. I was looking at R#'s code annotations and I see I can tell it what output to expect under limited conditions and it seems like that may be something I could leverage here, but I don't see any way to tell it that when the output is true/false/null/notnull, then a class variable (which has nothing to do with the input or output) will have a certain value type (true/false/null/notnull). Can something like this be done?
The use case here is this -- I have a dozen methods that all rely on the same preconditions, including several class variables being initialized. Rather than putting all those checks in each method, I want to have them all run the "DoPreChecks" method and if it returns true, we're good to go. The problem is that R# can't follow that and thinks I have lots of possible null reference exceptions. I could:
Ignore the errors completely and just tolerate wiggly lines everywhere
Disable and restore the warning at the beginning and ending of these methods
Disable the warning 1 line at a time
Do null checks or assertions before each use
The problem with each is...
Violates company policy to just ignore warnings
Disabling this check over large swaths of code would be worse than ignoring individual warnings because other valid issues may be there, but get disabled
This would require a LOT of R# comments, thus negating the helpfulness of DoPreChecks method
Same as #3
Right now I'm leaning toward getting an exception on the policy and just ignoring the warnings, but if there is a way to tell R# what is going on, that would be a much better solution. Can it be done without adding parameters or complicating the return type?
There is no contract annotation in ReSharper that sets up a relation between return value of a method and nullness of a field/property

Multithreaded GUI update() methods

I'm begginer in multithreading. I recently started to writing something like multithreaded observer. I need some clarification.
Let's say I'm working with Subject, and I'm changing its state. Then Observers (in example - GUI widgets) have to be notified, so they could perform the update() method.
And there is my question: how am i handling those getValue() performed by many Observers? If it's just a getter for some variable, do i have to run it in new thread? Does it require any locking?
Or mayby there is a metod to just send those new value to GUI thread, and letting widgets there access those value. And again, can it be a single loop, or do i have to create another threads for every widget to get those value?
That's a difficult subject. Here are couple of things that will guide and help you with it.
Embrace eventual consistency. When one object updates on one thread, others will receive change notifications and update to the correct state eventually. Don't try to keep everything in sync all the time. Don't expect everything to be up to date all the time. Design your system to handle these situations. Check this video.
Use immutability especially for collections. Reading and writing to a collection from multiple threads can result in disasters. Don't do it. Use immutable collections or use snapshotting. Basically one object that will called from multiple thread will return a snapshot of the state of the collection. when a notification for a change is received, the reader (GUI in your case) will request a snapshot of the new state and update it accordingly.
Design rich Models. Don't use AnemicModels that have only setters and getters and let others manipulate them. Let the Model protect it's data and provide queries for it's state. Don't return mutable objects from properties of an object.
Pass data that describes changes with change notifications. This way readers (GUI) may sync their state only from the change data without having to read the target object.
Divide responsibility. Let the GUI know that it's single threaded and received notifications from the background. Don't add knowledge in your Model that it will be updated on a background thread and to know that it's called from the GUI and give it the responsibility of sending change requests to a specific thread. The Model should not care about stuff like that. It raises notifications and let subscribers handle them the way they need to. Let the GUI know that the change notification will be received on the background so it can transfer it to the UI thread.
Check this video. It describes different way you can do multithreading.
You haven't shown any code or specified language, so I'll give you an example in pseudo code using a Java/C# like language.
public class FolderIcon {
private Icon mIcon;
public Icon getIcon() { return mIcon; }
public FolderIcon(Icon icon) {
mIcon = icon;
}
}
public class FolderGUIElement : Observer {
private Folder mFolder;
private string mFolderPath;
public FolderGUIElement(Folder folder) {
mFolder = folder;
mFolderPath = mFolder.getPath();
folder.addChangeListener(this);
}
public void onSubjectChanged(change c) {
if(c instanceof PathChange) {
dispatchOnGuiThread(() => {
handlePathChange((PathChange)change);
});
}
}
handlePathChange(PathChange change) {
mFolderPath = change.NewPath;
}
}
public class Folder : Subject {
private string mPath;
private FolderIcon mIcon;
public string getPath() { return mPath; }
public FolderIcon getIcon() { return mIcon; }
public void changePath(string newPath) {
mPath = patnewPath;
notifyChanged(new PathChange(newPath));
}
public void changeIcon(FolderIcon newIcon) {
mIcon = newIcon;
notifyChanged(new IconChange(newIcon));
}
}
Notice couple of things in the example.
We are using immutable objects from Folder. That means that the GUI elements cannot get the value of Path or FolderIcon and change it thus affecting Folder. When changing the icon we are creating a brand new FolderIcon object instead of modifying the old one. Folder itself is mutable, but it uses immutable objects for it's properties. If you want you can use fully immutable objects. A hybrid approach works well.
When we receive change notification we read the NewPath from the PathChange. This way we don't have to call the Folder again.
We have changePath and changeIcon methods instead of setPath and setIcon. This captures the intent of our operations better thus giving our model behavior instead of being just a bag of getters and setters.
If you haven't read Domain Driven Design I highly recommend it. It's not about multithreading, but on how to design rich models. It's in my list of books that every developer should read. On concept in DDD is ValueObject. It's immutable and provide a great way to implement models and is especially useful in multithreaded systems.

Defining aggregate roots when invariants exist within a list

I'm doing a family day care app, and thought I'd try DDD/CQRS/ES for it, but I'm running into issues with designing the aggregates well. The domain can be described pretty simply:
A child gets enrolled
A child can arrive
A child can leave
The goal is to track the times of the visits, generate invoices, put notes (eg. what was had for lunch, injuries etc.) against the visits. These other actions will be, by far, the most common interaction with the system, as a visit starts once a day, but something interesting happens all the time.
The invariant I'm struggling with is:
A child cannot arrive if they are already here
As far as I can see, I have the following options
1. Single aggregate root Child
Create a single Child aggregate root, with the events ChildEnrolled, ChildArrived and ChildLeft
This seems simple, but since I want each other event to be associated with a visit, it means the visit would be an entity of the Child aggregate, and every time I want to add a note or anything, I have to source all the visits for that child, ever. Seems inefficient and fairly irrelevant - the child itself, and every other visit, simply isn't relevant to what the child is having for lunch.
2. Aggregate Roots for Child and Visit
Child would source just ChildEnrolled, and Visit would source ChildArrived and ChildLeft. In this case, I don't know how to maintain the invariant, besides having the Visit take in a service for just this purpose, which I've seen is discouraged.
Is there another way to enforce the invariant with this design?
3. It's a false invariant
I suppose this is possible, and I should protect against multiple people signing in the same child at the same time, or latency meaning the use hits the 'sign in' button a bunch of times. I don't think this is the answer.
4. I'm missing something obvious
This seems most likely - surely this isn't some special snowflake, how is this normally handled? I can barely find examples with multiple ARs, let alone ones with lists.
Aggregates
You're talking heavily about Visits and what happened during this Visit, so it seems like an important domain-concept of its own.
I think you would also have a DayCareCenter in which all cared Children are enrolled.
So I would go with this aggregate-roots:
DayCareCenter
Child
Visit
BTW: I see another invariant:
"A child cannot be at multiple day-care centers at the same time"
"Hits the 'sign in' button a bunch of times"
If every command has a unique id which is generated for every intentional attempt - not generated by every click (unintentional), you could buffer the last n received command ids and ignore duplicates.
Or maybe your messaging-infrastructure (service-bus) can handle that for you.
Creating a Visit
Since you're using multiple aggregates, you have to query some (reliable, consistent) store to find out if the invariants are satisfied.
(Or if collisions are rarely and "canceling" an invalid Visit manually is reasonable, an eventual-consistent read-model would work too...)
Since a Child can only have one current Visit, the Child stores just a little information (event) about the last started Visit.
Whenever a new Visit should be started, the "source of truth" (write-model) is queried for any preceeding Visit and checked whether the Visit was ended or not.
(Another option would be that a Visit could only be ended through the Child aggregate, storing again an "ending"-event in Child, but this feels not so good to me...but that's just a personal opinion)
The querying (validating) part could be done through a special service or by just passing in a repository to the method and directly querying there - I go with the 2nd option this time.
Here is some C#-ish brain-compiled pseudo-code to express how I think you could handle it:
public class DayCareCenterId
{
public string Value { get; set; }
}
public class DayCareCenter
{
public DayCareCenter(DayCareCenterId id, string name)
{
RaiseEvent(new DayCareCenterCreated(id, name));
}
private void Apply(DayCareCenterCreated #event)
{
//...
}
}
public class VisitId
{
public string Value { get; set; }
}
public class Visit
{
public Visit(VisitId id, ChildId childId, DateTime start)
{
RaiseEvent(new VisitCreated(id, childId, start));
}
private void Apply(VisitCreated #event)
{
//...
}
public void EndVisit()
{
RaiseEvent(new VisitEnded(id));
}
private void Apply(VisitEnded #event)
{
//...
}
}
public class ChildId
{
public string Value { get; set; }
}
public class Child
{
VisitId lastVisitId = null;
public Child(ChildId id, string name)
{
RaiseEvent(new ChildCreated(id, name));
}
private void Apply(ChildCreated #event)
{
//...
}
public Visit VisitsDayCareCenter(DayCareCenterId centerId, IEventStore eventStore)
{
// check if child is stille visiting somewhere
if (lastVisitId != null)
{
// query write-side (is more reliable than eventual consistent read-model)
// ...but if you like pass in the read-model-repository for querying
if (eventStore.OpenEventStream(lastVisitId.Value)
.Events()
.Any(x => x is VisitEnded) == false)
throw new BusinessException("There is already an ongoning visit!");
}
// no pending visit
var visitId = VisitId.Generate();
var visit = new Visit(visitId, this.id, DateTime.UtcNow);
RaiseEvent(ChildVisitedDayCenter(id, centerId, visitId));
return visit;
}
private void Apply(ChildVisitedDayCenter #event)
{
lastVisitId = #event.VisitId;
}
}
public class CommandHandler : Handles<ChildVisitsDayCareCenter>
{
// http://csharptest.net/1279/introducing-the-lurchtable-as-a-c-version-of-linkedhashmap/
private static readonly LurchTable<string, int> lastKnownCommandIds = new LurchTable<string, bool>(LurchTableOrder.Access, 1024);
public CommandHandler(IWriteSideRepository writeSideRepository, IEventStore eventStore)
{
this.writeSideRepository = writeSideRepository;
this.eventStore = eventStore;
}
public void Handle(ChildVisitsDayCareCenter command)
{
#region example command douplicates detection
if (lastKnownCommandIds.ContainsKey(command.CommandId))
return; // already handled
lastKnownCommandIds[command.CommandId] = true;
#endregion
// OK, now actual logic
Child child = writeSideRepository.GetByAggregateId<Child>(command.AggregateId);
// ... validate day-care-center-id ...
// query write-side or read-side for that
// create a visit via the factory-method
var visit = child.VisitsDayCareCenter(command.DayCareCenterId, eventStore);
writeSideRepository.Save(visit);
writeSideRepository.Save(child);
}
}
Remarks:
RaiseEvent(...) calls Apply(...) instantly behind the scene
writeSideRepository.Save(...) actually saves the events
LurchTable is used as a fixed-sized MRU-list of command-ids
Instead of passing the whole event-store, you could make a service for it if you if benefits you
Disclaimer:
I'm no renowned expert. This is just how I would approach it.
Some patterns could be harmed during this answer. ;)
It sounds like the "here" in your invariant "A child cannot arrive if they are already here" might be an idea for an aggregate. Maybe Location or DayCareCenter. From there, it seems trivial to ensure that the Child cannot arrive twice, unless they have previously left.
Of course, then this aggregate would be pretty long-lived. You may then consider an aggregate for a BusinessDay or something similar to limit the raw count of child arrivals and departures.
Just an idea. Not necessarily the way to solve this.
I would try to base the design on reality and study how they solve the problem without software.
My guess is they use a notebook or printed list and start every day with a new sheet, writing today's date and then taking notes for each child regarding arrival, lunch etc. The case with kids staying the night shouldn't be a problem - checking in day 1 and checking out day 2.
The aggregate root should focus on the process (in your case daily/nightly per-child caring) and not the participating data objects (visit, child, parent, etc.).
I'm missing something obvious
This one; though I would quibble with whether or not it is obvious.
"Child" probably should not be thought of as an aggregate in your domain model. It's an entity that exists outside your model. Put another way, your model is not the "book of record" for this entity.
The invariant I'm struggling with is:
A child cannot arrive if they are already here
Right. That's a struggle, because your model doesn't control when children arrive and leave. It's tracking when those things happen in some other domain (the real world). So your model shouldn't be rejecting those events.
Greg Young:
The big mental leap in this kind of system is to realize that
you are not the book of record. In the warehouse example the
*warehouse* is the book of record. The job of the computer
system is to produce exception reports and estimates of what
is in the warehouse
Think about it: the bus arrives. You unload the children, scan their bar codes, and stick them in the play room. At the end of the day, you reverse the process -- scanning their codes as you load them onto the bus. When the scanner tries to check out a child who never checked in, the child doesn't disappear.
Your best fit, since you cannot prevent this "invariant violation", is to detect it.
One way to track this would be an event driven state machine. The key search term to use is "process manager", but in older discussions you will see the term "saga" (mis)used.
Rough sketch: your event handler is listening to these child events. It uses the id of the child (which is still an entity, just not an aggregate), to look up the correct process instance, and notifies it of the event. The process instance compares the event to its own state, generates new events to describe the changes to its own state, and emits them (the process manager instance can be re-hydrated from its own history).
So when the process manager knows that the child is checked in at location X, and receives an event claiming the child is checked in at location Y, it records a QuantumChildDetected event to track the contingency.
A more sophisticated process manager would also be acting on ChildEnrolled events, so that your staff knows to put those children into quarantine instead of into the playroom.
Working back to your original problem: you need to think about whether Visits are aggregates that exist within your domain model, or logs of things that happen in the real world.

BluetoothChat synchronized onResume Activity lifecycle method, why?

I'm studying right now the bluetooth Android API, and I ran into the BluetoothChat example.
http://developer.android.com/resources/samples/BluetoothChat/index.html
It contains many errors, first of all the simple fact that it uses API 11 but manifest does not force this minimum API.
Other interesting thing is the use of synchronized keyword on Activity lifecycle methods, like on onResume:
#Override
public synchronized void onResume() {
super.onResume();
if(D) Log.e(TAG, "+ ON RESUME +");
// Performing this check in onResume() covers the case in which BT was
// not enabled during onStart(), so we were paused to enable it...
// onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
if (mChatService != null) {
// Only if the state is STATE_NONE, do we know that we haven't started already
if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
// Start the Bluetooth chat services
mChatService.start();
}
}
}
Why this keyword is used there? Is there any reasonable explanation, or simply the one who wrote the code didn't know that onResume will be called always by the same thread? Or I miss something?
Thank you in advance!
This seems to be a pretty old question, but here's what I think may be going on:
My guess is that it wants to be careful about when "dialogs" return. The BluetoothChat example uses dialogs (as well as an overlay dialog-like activity) for enabling Bluetooth, enabling discovery, and initiating pairing/connections.
I don't know this for sure but I suspect there was a bug where different threads were returning to the main Activity and caused confusion as to how to handle onResume.
What they probably should have done is synchronize a block on an object and used flags to determine the state. That way the intention, state and functionality are more clear -- and the app knows what it should do in onResume;
something like this maybe:
//class fields
private Object myLockObj = new Object();
private boolean isPausedForPairing = false;
public void onResume()
{
super.onResume();
synchronized (myLockObj)
{
if (isPausedForPairing)
{
//handle a "pairing" onResume
}
}
}
However, due to it being an example app, they may have decided to go with something more simple. Example apps don't always follow convention because the idea is to demonstrate the particular code needed for the example. Sometimes following convention might add a lot of "distracting" code. Whether or not you agree with that is up to you though.

In sharepoint disabling a individual list item from being updated

What im wondering how to do is when someone edits a list item and it goes through my event code that is fired when a change is made and save is hit, i dont want anyone to be able to edit that list item itself while its still processnig that request. So i was wondering if while in that event i can disable the individual item from being edited by someone else untill it is done doing what it is doing.
Not sure if I understand exactly what you are want.
Try adding a field, hidden if you like, to the list or content type to use as a flag. When you enter your event code, make sure you check the flag first and if not set, set it and do your stuff. After you have done your stuff, unset the flag.
Here is some code to illustrate. Note that I have used a column named "updating". You can use the properties of the SPListItem as well if you do not care to add a column.
Oh, and don't forget to call DisableEventFiring before you to SPListItem.Update and then EnableEventFiring() afterwards. For get this and you will have a very nasty infinite loop on your hands.
.b
public override void ItemAdding(SPItemEventProperties properties)
{
if (properties.ListItem["updating"].ToString() == "updating")
{
properties.Cancel = true;
properties.ErrorMessage = "Item is currently updating, please try again later";
}
else
{
properties.ListItem["updating"] = "updating";
this.DisableEventFiring();
properties.ListItem.Update();
this.EnableEventFiring();
// do your stuff
properties.ListItem["updating"] = "";
this.DisableEventFiring();
properties.ListItem.Update();
this.EnableEventFiring();
}
}
I have no doubt that Bjørns solution will work but you have to be very carefull when implementing it.
Pls. remember at your updating method should include a "finally" that resets the flag, no matter which exception gets thrown, other wise your list will be locked down for ever :-(

Resources