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:
Live-Action TV
An episode of Coach featured <PERSON> in <PERSON>'s office throwing and sticking pencils up into the ceiling to the point it was literally covered in them. When <PERSON> kicks <PERSON> out of his office he slammed the door causing all the pencils to fall down.
In Dharma & Greg, episode 1, <PERSON> 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: <PERSON>, <PERSON>, and <PERSON> are throwing pencils at the ceiling. One falls and bounces up <PERSON>'s nose, which <PERSON> calls a miracle.
Combination of Live-Action TV and Real Life: Late Night with David Letterman. 5
Viewers know of <PERSON>'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", <PERSON> 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
Real Life
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. 900