SoFunction
Updated on 2025-04-12

Several Solutions for Calling an Asynchronous Method in Python Synchronous Method Not Blocking the Main Process

If you want toSynchronization methodCalling asynchronous methodsave_category_icon,andDo not block the main thread, can be usedasyncio.create_task()orthreading/To achieve it.

Solution 1: Use asyncio.create_task() (recommended)

If your codeRun in event loop(likeFlask + QuartorFastAPI), can be used:

import asyncio

async def save_category_icon(category_id=0, category_name=None):
    await (2)  # Simulate asynchronous tasks    print(f"Icon saved for category {category_id} - {category_name}")

def edit_category():
    loop = asyncio.get_event_loop()
    loop.create_task(save_category_icon(category_id=1, category_name="Test"))
    print("Main process continues...")  # Will not wait for the asynchronous task to complete
edit_category()

✅ advantage

  • It won't block the main thread
  • Tasks will be executed in the background
  • Suitable for runningasyncioEvent loop (FastAPI, Quart, etc.)

Solution 2: Use threading (suitable for Flask synchronization environment)

If your code isFlask(Synchronous framework) is recommended to usethreadingRunning asynchronous method:

import threading
import asyncio

def run_async_task():
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    loop.run_until_complete(save_category_icon(category_id=1, category_name="Test"))

def edit_category():
    (target=run_async_task, daemon=True).start()
    print("Main process continues...")  # Will not wait for the asynchronous task to complete
edit_category()

✅ advantage

  • The Flask main process will not be blocked
  • Asynchronous tasks can still be run in synchronous environments such as Flask
  • daemon=TrueEnsure that the thread is automatically closed when the process exits

Solution 3: Use (suitable for high concurrency situations)

If your asynchronous task isCPU intensiveOr better thread pool management is needed, you can use

import asyncio
from  import ThreadPoolExecutor

executor = ThreadPoolExecutor()

def run_async_task():
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    loop.run_until_complete(save_category_icon(category_id=1, category_name="Test"))

def edit_category():
    (run_async_task)  # Submit tasks to thread pool    print("Main process continues...")

edit_category()

✅ advantage

  • Suitable for high concurrency tasks
  • You can reuse ThreadPoolExecutor to improve performance
  • Don't block the main process

Which plan should I choose?

plan Applicable scenarios advantage
asyncio.create_task() The code has been run in the event loop (FastAPI, Quart) Lightweight, non-blocking
() Flask or Django (synchronous framework) Suitable for Flask, perform tasks in the background
High concurrency or multiple asynchronous tasks Suitable for CPU-intensive tasks

Recommend the best solution

  • FastAPI、Quart:✅ Useasyncio.create_task()
  • Flask, Django (synchronous):✅ Use()
  • High concurrency tasks:✅ Use

soAsynchronous tasks will run in the background and will not block the main process!

Summarize

This is the article about several solutions for calling asynchronous methods in Python synchronization methods that do not block the main process. For more related content on Python synchronization methods, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!