diff --git a/write.go b/write.go
index b1c57c1b9c35ffb04665b2146167403e74e0fa93..58bfdf9a61b97558d9ebec5644753106cdf301ec 100644
--- a/write.go
+++ b/write.go
@@ -257,7 +257,6 @@ func (c *Conn) writeFrame(ctx context.Context, fin bool, flate bool, opcode opco
 	if err != nil {
 		return 0, err
 	}
-	defer c.writeFrameMu.unlock()
 
 	// If the state says a close has already been written, we wait until
 	// the connection is closed and return that error.
@@ -268,6 +267,7 @@ func (c *Conn) writeFrame(ctx context.Context, fin bool, flate bool, opcode opco
 	wroteClose := c.wroteClose
 	c.closeMu.Unlock()
 	if wroteClose && opcode != opClose {
+		c.writeFrameMu.unlock()
 		select {
 		case <-ctx.Done():
 			return 0, ctx.Err()
@@ -275,6 +275,7 @@ func (c *Conn) writeFrame(ctx context.Context, fin bool, flate bool, opcode opco
 			return 0, c.closeErr
 		}
 	}
+	defer c.writeFrameMu.unlock()
 
 	select {
 	case <-c.closed: