File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -33,16 +33,25 @@ class FileMonitor(threading.Thread):
3333 def __init__ (self ):
3434 super ().__init__ (daemon = True )
3535 self .stop_flag = threading .Event ()
36+ self .loop_ready = threading .Event ()
3637 self .last_error_shown = None
3738 self .coroutines = []
3839 self .loop = None
40+ self ._lock = threading .Lock ()
3941
4042 def add_file_provider (self , file_provider : FileProvider ):
41- if self .loop :
42- task = asyncio .run_coroutine_threadsafe (
43- self ._check_file (file_provider ), self .loop
44- )
45- self .coroutines .append (task )
43+ # Wait indefinitely until the loop is ready
44+ self .loop_ready .wait ()
45+
46+ with self ._lock :
47+ if self .loop and not self .loop .is_closed ():
48+ future = asyncio .run_coroutine_threadsafe (
49+ self ._check_file (file_provider ), self .loop
50+ )
51+ self .coroutines .append (future )
52+ else :
53+ btul .logging .error (f"[{ LOGGER_NAME } ] Cannot add file provider, loop closed" )
54+
4655
4756 async def _check_file (self , file : FileProvider ):
4857 try :
@@ -83,6 +92,7 @@ async def _check_file(self, file: FileProvider):
8392 def run (self ):
8493 self .loop = asyncio .new_event_loop ()
8594 asyncio .set_event_loop (self .loop )
95+ self .loop_ready .set ()
8696
8797 async def monitor ():
8898 while not self .stop_flag .is_set ():
You can’t perform that action at this time.
0 commit comments