标签: coroutine

如何中断 Tornado 协程

假设我有两个像这样工作的函数:

@tornado.gen.coroutine
def f():
    for i in range(4):
        print("f", i)
        yield tornado.gen.sleep(0.5)

@tornado.gen.coroutine
def g():
    yield tornado.gen.sleep(1)
    print("Let's raise RuntimeError")
    raise RuntimeError
Run Code Online (Sandbox Code Playgroud)

通常,函数f可能包含无限循环并且永不返回(例如,它可以处理某个队列)。

我想要做的是能够在它产生的任何时候中断它。

最明显的方法不起作用。异常仅在函数f退出后引发(如果它是无穷无尽的,它显然永远不会发生)。

@tornado.gen.coroutine
def main():
    try:
        yield [f(), g()]
    except Exception as e:
        print("Caught", repr(e))

    while True:
        yield tornado.gen.sleep(10)

if __name__ == "__main__":
    tornado.ioloop.IOLoop.instance().run_sync(main)
Run Code Online (Sandbox Code Playgroud)

输出:

f 0
f 1
Let's raise RuntimeError
f 2
f 3
Traceback (most recent call last):
  File "/tmp/test/lib/python3.4/site-packages/tornado/gen.py", line 812, in run
    yielded = self.gen.send(value)
StopIteration

During handling …
Run Code Online (Sandbox Code Playgroud)

python yield exception tornado coroutine

2
推荐指数
1
解决办法
1906
查看次数

在 Unity Coroutine 中等待事件?

所以我有一个 Unity 协程方法,其中我有一些对象。这些对象代表从某处服务器收集的值,Updated它们在准备好时发送一个事件。

我想知道在 Unity 的协程中等待所有值更新的最佳方法是什么。

public IEnumerator DoStuff()
{
    foreach(var val in _updateableValues)
    {
        if (val.Value != null) continue;
        else **wait for val.Updated to be fired then continue**
    }
    //... here I do stuff with all the values
    // I use the WWW class here, so that's why it's a coroutine
}
Run Code Online (Sandbox Code Playgroud)

做这样的事情的最佳方法是什么?

谢谢!

c# coroutine unity-game-engine

2
推荐指数
1
解决办法
5663
查看次数

为什么VS2017协程不能返回void?

我正在使用目前在 VS2017 中进行实验的提议的 c++ 协程进行一些实验。我只是想拥有一个不返回任何内容的协同例程,而是在某个协同例程对象上调用 co_await,比方说,在恢复之前在另一个线程上进行一些处理。然而,VS 甚至不会编译返回 void 的最基本的协程程序。例如:

#include "stdafx.h"
#include <experimental\coroutine>

using namespace std::experimental;

void bob()
{
    co_await suspend_always{};
}

int main()
{
    bob();
}
Run Code Online (Sandbox Code Playgroud)

导致错误:

1>c:\program files (x86)\microsoft visual studio\2017\professional\vc\tools\msvc\14.10.25017\include\experimental\resumable(46): error C2825: '_Ret': must be a class or后跟'::'时的命名空间 1>d:\dev\coroutinestest\main.cpp(10):注意:请参阅对正在编译的类模板实例化 'std::experimental::coroutine_traits' 的引用 1>c:\program files (x86)\microsoft visual studio\2017\professional\vc\tools\msvc\14.10.25017\include\experimental\resumable(46):错误 C2510:'_Ret':'::' 的左边必须是一个类/结构/union 1>c:\program files (x86)\microsoft visual studio\2017\professional\vc\tools\msvc\14.10.25017\include\experimental\resumable(46):错误 C2061:语法错误:标识符“promise_type” 1>c:\program files (x86)\microsoft visual studio\2017\professional\vc\tools\msvc\14.10.25017\include\experimental\resumable(46): 错误 C2238: ';' 之前的意外标记

现在我假设这个错误是由于 void::promise_type 是无意义的,但是为什么在没有任何返回的情况下甚至会实例化 promise 类型?我希望能够从协程中返回任何内容。这只是实现中的当前错误还是我误解了协同程序的使用。

谢谢

c++ coroutine visual-studio visual-studio-2017

2
推荐指数
1
解决办法
1593
查看次数

为什么 await 不等待 asyncio.create_subprocess_exec()

我正在编写一个协程来根据教程在 python 中执行 shell 命令。这里是基本的:

import asyncio

async def async_procedure():
    process = await asyncio.create_subprocess_exec('ping', '-c', '2', 'google.com')
    await process.wait()
    print('async procedure done.')

loop = asyncio.get_event_loop()
loop.run_until_complete(async_procedure())
loop.close()
Run Code Online (Sandbox Code Playgroud)

上面的这段代码工作得很好。它给出了这样的结果:

PING google.com (...) 56(84) bytes of data.
64 bytes from ...: icmp_seq=1 ttl=46 time=34.8 ms
64 bytes from ...: icmp_seq=2 ttl=46 time=34.5 ms

--- google.com ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 3004ms
rtt min/avg/max/mdev = 33.771/34.437/34.881/0.407 ms
Process done!
Run Code Online (Sandbox Code Playgroud)

当我尝试删除 process.wait() 时:

async def async_procedure():
    await …
Run Code Online (Sandbox Code Playgroud)

python asynchronous coroutine python-asyncio

2
推荐指数
1
解决办法
4388
查看次数

在 unity3d 中运行时结束协程

我试图用一个按钮开始和结束一个协程。我可以启动协程,但我不能停止它,如果我在第一次启动协程后再次单击该按钮,它只会再次重新启动并且滑块值上升。

继承人我的代码

    public void LoopButton(){

    if (lb == 1){
        StopCoroutine (AutoLoop());
        tb--;
    } else {
        StartCoroutine (AutoLoop ());
        tb++;
    }
}

IEnumerator AutoLoop(){

    slider.value = slider.minValue;

    while(slider.value < slider.maxValue){
        slider.value++;
        yield return new WaitForSeconds(0.5f);
    }

    StartCoroutine (AutoLoop());
}
Run Code Online (Sandbox Code Playgroud)

c# loops coroutine unity-game-engine

2
推荐指数
1
解决办法
1128
查看次数

E/AndroidRuntime:致命异常:main 和 Coroutine,Retrofit2

我刚开始学习 kotlin,我的第一个应用程序使用 Retrofit2 和 Coroutine,但是有问题。我有一些错误,但是通过协程,堆栈跟踪的信息非常差。也许有人会发现错误或知道 hot 以使堆栈跟踪信息更丰富。

服务:

const val API_KEY = "Bcae2032bb596c73b10bdab625c037da"

interface CurrencyApi {

//https://api.currencystack.io/currency?base=USD&target=EUR&apikey=Bcae2032bb596c73b10bdab625c037da

@GET("currency")
fun getCurrentCurrency(
    @Query("base") base: String,
    @Query("target") target: String
): Deferred<Currency>

companion object {
    operator fun invoke(): CurrencyApi {
        val requestInterceptor = Interceptor { chain ->

            val url = chain.request()
                .url()
                .newBuilder()
                .addQueryParameter("key", API_KEY)
                .build()
            val request = chain.request()
                .newBuilder()
                .url(url)
                .build()

            return@Interceptor chain.proceed(request)
        }

        val okHttpClient = OkHttpClient.Builder()
            .addInterceptor(requestInterceptor)
            .build()

        return Retrofit.Builder()
            .client(okHttpClient)
            .baseUrl("https://api.currencystack.io/")
            .addCallAdapterFactory(CoroutineCallAdapterFactory())
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(CurrencyApi::class.java)
    }
}
Run Code Online (Sandbox Code Playgroud)

活动:

 class …
Run Code Online (Sandbox Code Playgroud)

android coroutine kotlin retrofit2 kotlinx.coroutines

2
推荐指数
1
解决办法
3528
查看次数

在 Kotlin 中创建异步函数

我正在尝试在 kotlin 协程中创建一个异步函数,这是我按照教程尝试的:

fun doWorkAsync(msg: String): Deferred<Int> = async {
    delay(500)
    println("$msg - Work done")
    return@async 42
}
Run Code Online (Sandbox Code Playgroud)

但是在这段代码中async,编译器无法解决,但教程视频显示它运行良好。是不是因为教程使用了旧的 Kotlin 协程的做事方式?那么,如果是这样如何创建异步函数呢?

coroutine kotlin kotlin-coroutines

2
推荐指数
1
解决办法
2312
查看次数

协程中的值为真后无法返回字符串

我在运行这个协程时遇到了问题。它一直吐出一个错误,说它不能将 WaitUntil 转换为字符串,当我将 WaitUntil 添加到返回类型时,它又吐出另一个说它无法返回。我已经尝试研究了几个小时,但无济于事。这是代码的片段:

     public string OpenSaveDialog(string Title, string OpenLocation, string[] AllowedExtentions)
     {
         OpenBtn.GetComponentInChildren<TMPro.TMP_Text>().text = "Save";
         TitleText.text = Title;
         AllowFileNameTyping = true;
         MultiSelect = false;

         LoadIntoExplorer(PathInput, AllowedExtentions);

         return StartCoroutine(WaitForFinish()); // Error here: Cannot implicitly convert type 'UnityEngine.Coroutine' to 'string'
     }

     IEnumerator<string> WaitForFinish()
     {
         yield return new WaitUntil(() => Done == true); // Error here: Cannot implicitly convert type 'UnityEngine.WaitUntil' to 'string'
         yield return FilePathsSelected[0];
     }
Run Code Online (Sandbox Code Playgroud)

c# return coroutine unity-game-engine

2
推荐指数
1
解决办法
378
查看次数

Spring WebFlux Reactive 和 Kotlin Coroutines 启动错误

无论我如何设置我的项目,我都会在启动时遇到以下异常:

“检测到不支持的挂起处理程序方法”。

我正在尝试使用https://docs.spring.io/spring/docs/5.2.0.BUILD-SNAPSHOT/spring-framework-reference/languages.html#coroutines 中描述的对协程的支持。

这是我的 gradle 设置(缩写)。我如何摆脱这个异常?

ext.kotlin_version = '1.3.70'
ext.kotlin_coroutines_core = '1.3.5'
ext.kotlin_coroutines_reactor = '1.3.5'
ext.spring_boot_version = '2.2.6.RELEASE'
ext.springfox_version='2.9.2'
ext.jackson_module_kotlin = '2.10.3'
...

implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$kotlin_coroutines_core"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-reactor:$kotlin_coroutines_reactor"
implementation "org.springframework.boot:spring-boot-starter-webflux:$spring_boot_version"
implementation "com.fasterxml.jackson.module:jackson-module-kotlin:$jackson_module_kotlin"
implementation "net.rakugakibox.spring.boot:logback-access-spring-boot-starter:2.7.1"
implementation "net.logstash.logback:logstash-logback-encoder:5.3"
implementation "org.springframework.boot:spring-boot-starter-actuator:$spring_boot_version"
implementation "io.micrometer:micrometer-registry-statsd:1.1.4"
implementation "io.springfox:springfox-swagger2:$springfox_version"
Run Code Online (Sandbox Code Playgroud)

exception coroutine kotlin spring-boot spring-webflux

2
推荐指数
1
解决办法
1261
查看次数

协程块中的方法如何在 Kotlin 中工作?

协程有两种类型。堆叠和无堆叠。而 Kotlin 协程是无栈协程。

另一方面,一旦一个方法被调用,它就会被堆叠在内存中。我们可以使用方法进行递归调用。

在 Kotlin 中,我需要做的就是suspend为协程上下文中调用的方法添加关键字。

它没有堆栈,那么它是如何工作的?

我的猜测是,由于协程对象属于某个线程,因此该线程拥有它们。让我们说,是的。那么它是如何在引擎盖下工作的呢?

coroutine kotlin kotlin-coroutines kotlin-coroutines-flow

2
推荐指数
1
解决办法
77
查看次数