在断开连接的情况下将同步代码包装到异步等待中 [英] Wrap synchronous code into async await in disconnected scenario

查看:89
本文介绍了在断开连接的情况下将同步代码包装到异步等待中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下客户端-服务器样式的伪代码:

I have the following client-server style pseudo-code:

public void GetGrades() {
   var msg = new Message(...); // request in here
   QueueRequest?.Invoke(this, msg); // add to outgoing queue
}

在另一个处理器类中,我有一个循环:

In another processor class I have a loop :

// check for messages back from server
// server response could be a "wait", if so, wait for real response
// raise MessageReceived event here
// each message is then processed by classes which catch the event

// send new messages to server
if (queue.Any()){
  var msg = queue.Dequeue();
  // send to server over HTTP 
}

我已经大大简化了这段代码,因此很容易看到我的问题的目的.

I have heavily simplified this code so its easy to see the purpose of my question.

目前,我将这样的代码称为:

Currently I call this code like so:

student.GetGrades(); // fire and forget, almost

但是我不太了解结果何时返回,我基本上使用事件:

But I have a less than ideal way of knowing when the result comes back, I basically use events:

我举起MessageReceived?.Invoke(this, msg);,然后在另一个级别StudentManager抓住,这将结果设置在特定的学生对象上.

I raise MessageReceived?.Invoke(this, msg); then catch this at another level StudentManager which sets the result on the specific student object.

但是相反,我想将其包装在async await中,并具有如下内容:

But instead I would like to wrap this in async await and have something like so:

var grades = await GetGrades();

在这种脱节的情况下这可能吗?我将如何去做呢?

Is this possible in such disconnected scenarios? How would I go about doing it?

推荐答案

您可以尝试使用

You could try using a TaskCompletionSource. You could do something like this

TaskCompletionSource<bool> _tcs; 
public Task GetGrades() {
   var msg = new Message(...); // request in here
   QueueRequest?.Invoke(this, msg); // add to outgoing queue
   _tcs = new TaskCompletionSource<bool>();
   return _tcs;
}

然后,当您需要确认任务已完成时,请执行此操作.

And then when you need to confirm that the task was completed you do.

_tcs.TrySetResult(true);

通过此操作,您可以执行以下操作:

By doing this you can do:

var grades = await GetGrades();

当然,这里还有其他事情要解决.如果您可以打很多电话,将把那些TaskCompletionSource保存在哪里,以及如何将每条消息链接到每个TaskCompletionSource.但我希望您能掌握基本的想法.

Of course there are another things to solve here. Where you are going to keep those TaskCompletionSource if you can many calls, and how you can link each message to each TaskCompletionSource. But I hope you get the basic idea.

这篇关于在断开连接的情况下将同步代码包装到异步等待中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆