[Update: The Target Display Mode didn't work again after 2 months.]
I had an older iMac that supports Target Display Mode. However, over the last year, it has become less reliable. When connected with my MacBook Pro, the Target Display Mode might sometimes last only a short period of time (e.g. one hour or less) and then disconnect. I tried to update the macOS version to the latest one but it couldn't help.
I finally seem to have found a solution to this problem. Since my iMac now mainly use as a display, I re-installed an older version of Mac OS X (10.8.5) on it. The Target Display Mode has been working properly over the last two weeks. I hope this will continue to work in the future.
For reference, I installed also KeyRemap4MacBook 8.4.0 to allow using a PC keyboard to trigger the Target Display Mode on the iMac.