This is an example of Art Imitates Life but that's not the TVTrope link you need.
This is the TVTropes link you deserve Object Ceiling Cling
Basically, in storytelling, it's a comedic effect to have things stuck in the ceiling and maybe fall after.
However, there are specific pencil references in that link:
An episode of Coach featured Luther in Hayden's office throwing and sticking pencils up into the ceiling to the point it was literally covered in them. When Hayden kicks Luther out of his office he slammed the door causing all the pencils to fall down.
In Dharma & Greg, episode 1, Greg is shown in his new law office throwing a couple pencils at the ceiling. The camera pans up to show a couple dozen pencils already stuck in the tiles above his desk. Later, he throws one more pencil above his head, only to have all the others fall out of the ceiling onto him.
How I Met Your Mother: Marshall, Barney, and Ted are throwing pencils at the ceiling. One falls and bounces up Barney's nose, which Marshall calls a miracle.
Combination of Live-Action TV and Real Life: Late Night with David Letterman. Viewers know of Dave's tendency to flip pencils up out of view coming out of commercial break. Studio audience members get to see the result; the fake acoustic ceiling above the desk is peppered with pencils, and his accuracy is epic (I went to half a dozen shows and he didn't miss once).
The X-Files: episode "Chinga", Mulder spends his spare time throwing pencils into the ceiling over his desk.
The very last one is probably the one you reference in your question. HIMYM (the other show was probably contemporary to Castle) but Coach was late 80's and Dharma & Greg was early 90's
The link goes on further to
Kids in school launch pencils up at ceilings which have small holes just small enough for the pencil to stick in
Office workers who work in buildings with fake ceilings often throw pencils into the ceiling, as the fake ceilings are often as weak as cardboard. Parodied in [a] Bud Light commercial.
It is a visual cue of boredom, ennui; in Spanish we say "ocio" where in English there is a saying "Idle hands are the Devil's tools". Not sure where in the world you hail from, but there may be an international equivalent you are familiar with.