Try to get out of going, if possible.
If not, make a plan in advance.
Schedule how long you have to be there, and stick to it.
Set an alarm to remind you when to leave.
Prepare an excuse to leave in advance.
Give yourself a pep-talk before going.
Look at yourself in the mirror and tell your eyes, "today, we won't stray!"
Bring a sefer or a book to read instead of "mingling".
Avoid socializing with the opposite gender as much as possible
Sit facing away from the opposite gender.