Skip to content

Commit d113534

Browse files
authored
Merge pull request #8 from GhostTypes/perf/async-file-io-thumbnail-9917476809116768482
⚡ Optimize blocking file I/O in thumbnail save
2 parents 9b070fc + 7ad49a9 commit d113534

1 file changed

Lines changed: 10 additions & 3 deletions

File tree

flashforge/tcp/parsers/thumbnail_info.py

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
44
Handles the parsing, storage, and manipulation of 3D print file thumbnail images.
55
"""
6+
import asyncio
67
import base64
78
from pathlib import Path
89
from typing import Optional
@@ -119,6 +120,12 @@ def to_base64_data_url(self) -> Optional[str]:
119120
base64_data = base64.b64encode(self._image_data).decode('ascii')
120121
return f"data:image/png;base64,{base64_data}"
121122

123+
@staticmethod
124+
def _write_file_sync(file_path: str, data: bytes) -> None:
125+
"""Helper to write bytes to a file synchronously."""
126+
with open(file_path, 'wb') as f:
127+
f.write(data)
128+
122129
async def save_to_file(self, file_path: Optional[str] = None) -> bool:
123130
"""
124131
Saves the thumbnail image data to a file.
@@ -149,9 +156,9 @@ async def save_to_file(self, file_path: Optional[str] = None) -> bool:
149156
print("ThumbnailInfo: No file path provided and no filename to generate one from")
150157
return False
151158

152-
# Write the bytes to file
153-
with open(file_path, 'wb') as f:
154-
f.write(self._image_data)
159+
# Write the bytes to file in a separate thread to avoid blocking the event loop
160+
loop = asyncio.get_running_loop()
161+
await loop.run_in_executor(None, self._write_file_sync, file_path, self._image_data)
155162

156163
print(f"ThumbnailInfo: Saved thumbnail to {file_path}")
157164
return True

0 commit comments

Comments
 (0)