从文档中我意识到我可以使用Caliburn Micro的协同程序进行异步操作.开箱即用,没有额外的技术.所以我在Windows Phone应用程序中实现了下一个代码:
public class SimpleViewModel : Screen
{
// ...
protected override void OnViewLoaded(object view)
{
base.OnViewLoaded(view);
Coroutine.BeginExecute(RunTask());
}
public IEnumerator<IResult> RunTask()
{
yield return new SimpleTask();
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
SimpleTask:
public class SimpleTask : IResult
{
public void Execute(ActionExecutionContext context)
{
Thread.Sleep(10000);
}
public event EventHandler<ResultCompletionEventArgs> Completed;
}
Run Code Online (Sandbox Code Playgroud)
我希望Execute方法中的代码将运行异步.但这不会发生.我的UI线程被阻止了10秒钟.
我犯了哪个错误?或者我对协同程序的异步性质的假设是错误的?
我试图在更新功能中调用拍摄动画,然后在产生激光镜头之前等待0.5秒.以下代码对我不起作用.我该怎么做才能达到预期的效果?
void Update()
{
if (Input.GetMouseButtonDown (0))
{
animator.SetTrigger("Shoot"); // Start animation
WaitAndShoot();
}
}
IEnumerator WaitAndShoot()
{
yield return new WaitForSeconds(0.5f);
Instantiate (shot, shotSpawn.transform.position,shotSpawn.transform.rotation);
}
Run Code Online (Sandbox Code Playgroud) 我有一个BonusController脚本作为BonusgameObject的一个组件.这个奖金必须在碰撞时销毁,但必须"行动"几秒钟.我为此启动了一个协同程序,但脚本停止执行(我认为这是因为我将gameObject设置为非活动状态).这是代码BonusController:
void OnTriggerEnter2D(Collider2D col)
{
StartCoroutine(speedUp(1));
gameObject.SetActive(false);
}
IEnumerator speedUp(float seconds)
{
Debug.Log("before");
yield return new WaitForSeconds(seconds);
Debug.Log("after"); // <--- This is never called
}
Run Code Online (Sandbox Code Playgroud)
如何删除对象并且不停止协程脚本执行?
如果我正确理解goroutine在系统线程之上的工作方式-它们从队列中一个接一个地运行。但这是否意味着每个goroutine都会将其上下文加载/卸载到CPU?如果是,系统线程和goroutines之间有什么区别?
最重要的问题是上下文切换的时间成本。这是对的吗?
检测哪种goroutine请求哪些数据的基础是什么?例如:我正在从goroutine A向DB发送请求,并且不等待响应,并且同时切换到下一个goroutine。系统如何理解请求来自A而不是来自B或C?
试图在python中了解更多的generator/send函数.我在链接中读到了一些内容:生成器发送功能的目的,帮助了很多.
但我想了解下面的代码.为什么有next(checker)必要?发送功能是否自动询问发电机中的下一个项目?我尝试next(checker)过在for循环之前,但是它的功能不同.我认为send函数将'attempt'作为x发送并产生是否x == password.我只是不明白为什么必须在循环中使用下一个(检查器).
def checkPassword(attempts, password):
def check():
while True:
x = yield
yield x == password
checker = check()
for i, attempt in enumerate(attempts):
next(checker)
if checker.send(attempt):
return i + 1
return -1
Run Code Online (Sandbox Code Playgroud)
上述功能基于以下问题:
"为了验证你的功能,你想在本地测试它.给定一个尝试列表和正确的密码,返回第一次正确尝试的从1开始的索引,如果没有则返回-1.
例
对于attempts = ["hello", "world", "I", "like", "coding"]和
password = "like",输出应为checkPassword(尝试,密码)= 4."
我需要从外部服务为我的系统并行获取多个字段(在此示例中,由Name(),Age()和CanDrive()方法模拟)。
fetchUser()方法可以实现我想要的功能,但是如果您认为我可以有10个以上的字段,那么它似乎太冗长了。有没有更好的方法可以实现这一目标?
游乐场:https : //play.golang.org/p/90sNq1GmrD8
代码(与游乐场相同):
package main
import (
"fmt"
"sync"
)
type User struct {
Name string
Age int
CanDrive *bool
}
func Name() (string, error) {
return "foobar", nil
}
func Age() (int, error) {
return 25, nil
}
func CanDrive() (bool, error) {
return true, nil
}
func fetchUser() (*User, error) {
var wg sync.WaitGroup
errs := make(chan error)
user := &User{}
wg.Add(1)
go func() {
var err error
defer wg.Done()
user.Name, err = Name() …Run Code Online (Sandbox Code Playgroud) 谁能解释我为什么人们应该使用协程?是否有一些协程代码示例显示了比常规Java并发代码更好的完成时间(没有神奇的delay()函数,没有人delay()在生产中使用)?
在我的个人示例中,协程(第1行)反对Java代码(第2行)。也许我做错了什么?
例:
import kotlinx.coroutines.*
import java.time.Instant
import java.util.concurrent.CompletableFuture
import java.util.concurrent.Future
@ExperimentalCoroutinesApi
fun main() = runBlocking {
val begin = Instant.now().toEpochMilli()
val jobs = List(150_000) {
GlobalScope.launch { print(getText().await()) } // :1
// CompletableFuture.supplyAsync { "." }.thenAccept { print(it) } // :2
}
jobs.forEach { it.join() }
println(Instant.now().toEpochMilli() - begin)
}
fun getText(): Future<String> {
return CompletableFuture.supplyAsync {
"."
}
}
@ExperimentalCoroutinesApi
suspend fun <T> Future<T>.await(): T = suspendCancellableCoroutine { cont ->
cont.resume(this.get()) {
this.cancel(true)
} …Run Code Online (Sandbox Code Playgroud) 所以我制作了一个应用程序,我试图在单击按钮时显示进度条。
仅当我将View.VISIBLE放在处理程序之外时它才会显示。
科特林代码:
button.setOnClickListener {
progressBar.visibility = View.VISIBLE
runBlocking {
try {
//HTTP request removed because of confidentiality, assume I'm setting delay
} catch (e: Exception) {
Log.e(tag, "Error: " + e.message)
Toast.makeText(this@MainActivity, "Could not find page", Toast.LENGTH_LONG)
.show()
}
}
progressBar.visibility = View.GONE
}
Run Code Online (Sandbox Code Playgroud)
按钮 XML:
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyle"
android:alpha="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility= "invisible"/>
Run Code Online (Sandbox Code Playgroud)
我已经搜索了几个小时,但找不到与我的案例相关的内容。
想要的输出: 获取单击按钮时的进度条。
在我下面的简单 asyncio 代码中,应用程序有一个任务self.add_item_loop_task不断地向asyncio.Queuenamed 中添加一个整数self.queue,而第二个任务则self.get_item_loop_task不断地等待将某些内容添加到队列中并将print其退出。
但是,这个应用程序0在我运行时只打印一次,然后卡在那里。我相信循环self.get_item_loop_task没有继续。为什么会这样?
import asyncio
class App:
def __init__(self):
self.queue = asyncio.Queue()
async def start(self):
self.add_item_loop_task = asyncio.create_task(self.add_item_loop())
self.get_item_loop_task = asyncio.create_task(self.get_item_loop())
await asyncio.wait(
[
self.add_item_loop_task,
self.get_item_loop_task,
]
)
async def stop(self):
self.add_item_loop_task.cancel()
self.get_item_loop_task.cancel()
async def add_item_loop(self):
i = 0
while True:
await self.queue.put(i)
i += 1
await asyncio.sleep(1)
async def get_item_loop(self):
while True:
item = await self.queue.get()
print(item)
app = App()
try:
asyncio.run(app.start())
except …Run Code Online (Sandbox Code Playgroud) 如何让下面的流量收集器收到“hello”?收集器正在调用,myFunction1()而收集器又调用myFunction2(). 两者都是挂起函数。
目前,当我点击运行并且没有收到流量时,什么也没有发生。我在这里错过了什么吗?
CoroutineScope(IO).launch {
val flowCollector = repo.myFunction1()
.onEach { string ->
Log.d("flow received: ", string)
}
.launchIn(GlobalScope)
}
Run Code Online (Sandbox Code Playgroud)
class Repo {
suspend fun myFunction1(): Flow<String> = flow {
/*some code*/
myFunction2()
}
suspend fun myFunction2(): Flow<String> = flow {
/*some code*/
emit("hello")
}
}
Run Code Online (Sandbox Code Playgroud) 我正在用现代C++20编写我的项目。这个应用程序就像图形模式下的终端/控制台,您可以在其中输入带有各自参数的命令,终端将识别第一个单词,如果在其内部映射中找到它,它会调用映射函数(命令本身) 。这很好用。但现在,我意识到有些命令需要用户交互。例如,如果我想从MS-DOS重新创建del命令,并且用户键入,该命令将需要从键盘获取一个字符(表示是,表示否)。其他一些命令将要求用户键入整个字符串。我怎样才能做到这一点?我正在考虑将我的命令实现为协程,这样我就可以暂停执行,让终端知道我想要单个字符或完整字符串,然后恢复。但我发现协程有点复杂。到目前为止,我有这段代码del *.bak /pyn
enum class e_command_input { SINGLE_CHAR, STRING };
class OS_Command
{
public:
// Forward declaration
struct promise_type;
using t_handle = std::coroutine_handle<promise_type>;
struct promise_type
{
// Creates the command
auto get_return_object() -> OS_Command
{
return OS_Command{ t_handle::from_promise(*this) };
}
auto initial_suspend() -> std::suspend_always
{
cout << " Command starts running" << endl;
return {};
}
auto final_suspend() noexcept -> std::suspend_always
{
cout << " Command finishes …Run Code Online (Sandbox Code Playgroud) 我正在制作一个 2d 游戏,我需要淡入和淡出一些元素。
IEnumerator FadeOut(Renderer rend, float speed)
{
while (rend.material.color.a > 0)
{
Color objectColor = rend.material.color;
float fadeAmount = objectColor.a - (speed * Time.deltaTime);
objectColor = new Color(objectColor.r, objectColor.g, objectColor.b, fadeAmount);
rend.material.color = objectColor;
yield return null;
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的 FadeOut 协程(FadeIn脚本正是这个协程,但相反)。问题是它会出现错误。例如,如果我多次进入和退出需要淡出的区域,则整个游戏只会混合黑色(或太亮)。我通过使用StopAllCoroutines函数解决了这个问题。协程调用之一:
StopAllCoroutines();
StartCoroutine(FadeOut(tilemap,1f));
Run Code Online (Sandbox Code Playgroud)
我宁愿不使用 StopAllCoroutines,因为我在同一游戏中使用多个协程,进入淡入淡出区域只会关闭一半的系统。
我尝试使用StopCoroutine("name")(但据我所知,它与较新版本的 unity 不兼容)。我还在 StackOverflow 上找到了另一个帖子
来自线程的代码:
routines[col] = StartCoroutine((DamageEverySecond(health, damageRate)));
[...]
StopCoroutine(routine);
Run Code Online (Sandbox Code Playgroud)
不幸的是,这并不能解决我的问题,因为有多个实例同时运行。
我怎么解决这个问题?
嗨我在c#中的脚本的以下协程部分有问题.我得到的错误信息附在屏幕抓取中,似乎是:GetComponent<Renderer>().
using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
public class test: MonoBehaviour
{
public float model2;
public float model1;
public void section1()
{
SceneManager.LoadScene("section1", LoadSceneMode.Single);
}
public void fade()
{
StartCoroutine(colorlerpin());
}
public IEnumerator colorlerpin()
{
float ElapsedTime2 = 0.0f;
float TotalTime2 = 1f;
while (ElapsedTime2 < TotalTime2)
{
// fades out main heart
ElapsedTime2 += Time.deltaTime;
model1.GetComponent<Renderer>().material.color = Color.Lerp(new Color(1f, 1f, 1f, 1f), new Color(1f, 1f, 1f, 0f), (ElapsedTime2 / TotalTime2));
yield return null;
// fades in cutaway …Run Code Online (Sandbox Code Playgroud) coroutine ×13
c# ×5
kotlin ×3
go ×2
goroutine ×2
python ×2
android ×1
asynchronous ×1
c++ ×1
concurrency ×1
generator ×1
java ×1
kotlin-flow ×1
oculus ×1
python-3.x ×1
queue ×1
suspend ×1
unity5 ×1