Senator Bob Casey, a three-term Democrat from Pennsylvania long seen as an institution in state politics, was defeated on Thursday by his Republican challenger, the former hedge-fund executive David McCormick, in a stunning upset in one of the nation’s top Senate races.

Mr. Casey conceded on Thursday shortly before The New York Times called the race for Mr. McCormick, whose lead of less than half a percentage point had triggered a recount. As Republicans looked to add Pennsylvania to their win column after seizing control of the Senate, the post-election period set off a legal battle between the two sides.

“This race was one of the closest in our commonwealth’s history,” Mr. Casey said in a statement. “I am grateful to the thousands of people who worked to make sure every eligible vote cast could be counted.”

In his second time running for Senate in Pennsylvania, Mr. McCormick channeled the sour national mood into a victory over a well-established incumbent in a top battleground state. Republicans will now hold a 53-to-47 advantage in the Senate in addition to narrowly controlling the House, giving President-elect Donald J. Trump more flexibility to pursue his agenda.