Wrap synchronous code into async await in disconnected scenario

与世无争的帅哥 提交于 2020-01-16 14:49:08

问题


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:

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

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?


回答1:


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();

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.



来源:https://stackoverflow.com/questions/55400253/wrap-synchronous-code-into-async-await-in-disconnected-scenario

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!