将同步重写为异步:不等待功能

时间:2019-07-09 00:53:42

标签: python asynchronous sanic

当我阅读更多内容时,我对使用python的aysnc感到更加愚蠢。因此,我决定要求直接回答。如何更改以下代码(使用异步或类似方法)以获得所需的结果?另外,我该怎么用烧瓶或Sanic呢?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;




public class PlayerController : MonoBehaviour
{
    private float rotation = 0f;
    public GameObject wheele;
    private float xMin = -1.0f, xMax = 1.0f;
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.UpArrow))
        {
            if (rotation >= -90)
                transform.parent.transform.Rotate(new Vector3(0.0f, 0.0f, rotation));

            rotation -= 8;
            //Mathf.Clamp(rotation, -90.0f, 0);
        }
        if(Input.GetKeyDown(KeyCode.DownArrow))
        {
            if (rotation >= -90)
                transform.parent.transform.RotateAround(wheele.transform.position, Vector3.up,20);

            rotation += 2;
            Mathf.Clamp(rotation, -90.0f, 0);
        }


    }
}

基本上,我不希望在返回我的main_job之前等待long_job结束。先感谢您。 :)

1 个答案:

答案 0 :(得分:2)

等待asyncio的sleep()来让时间从事其他工作(如果您不需要等待其他事情)。 使用create_task()而不是await来开始作业而不会阻塞。 最后,您必须使用事件循环来开始主要工作。

# Written in Python 3.7
import asyncio

async def long_job():
    print('long job started')
    await asyncio.sleep(5)
    print('long job ended')

async def main_job():
    asyncio.create_task(long_job())
    await asyncio.sleep(1)
    print('main job returned')

您的框架应该启动事件循环,您不必自己启动它。您可以通过框架调用的await函数create_taskmain_job()或在async def上调用asyncio.run(),这取决于您是否要阻止。


如果要在没有框架的情况下进行测试,则必须使用async def loop_job(): asyncio.create_task(main_job()) while len(asyncio.Task.all_tasks()) > 1: # Any task besides loop_job()? await asyncio.sleep(0.2) asyncio.run(loop_job()) 自己开始循环。即使其他任务尚未完成,它也会在任务完成后立即停止。但这很容易解决:

loop.run_forever()

如果您自己实现框架,则可以使用更原始的stop(),但您必须自己pip install django-cors-headers