简体   繁体   中英

Wrap synchronous code into async await in disconnected scenario

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM