调用异步方法 [英] call asynchronous methods

查看:104
本文介绍了调用异步方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我正在尝试在一种方法中使用两种异步方法.
方法如下:

Hi,

I''m trying to use two asynchronous methods in one method.
the methods look like this:

class Sender
{
   public static void sendMessage(Int32 uniqueRequestID, Int32 requestCode
}

class Receiver : IReceiver
{
   public override void onAnswerReceive(Int32 uniqueRequestID, Answer answer) 
   { 
       ... 
   }
}



而我正试图拥有这个:



and I''m trying to have this:

class Client
{
   private Receiver;

   Data getData(Int32 code)
   {
       Int32 id = this.CreateNewUniqueID();
       Sender.sendMessage(id, code);
       ....?
       return new Data(answerIGotSomehowFromReceiverOnAnswerReceive);
   }
}



还需要为很多答案调用Receiver.onAnswerReceive,请求和答案之间的链接是Int32 uniqueRequestID.

所以我有两个问题:
1.如何等待答案?
2.如何从C#4.0中的getData方法访问Answer?
(我看过一些有关异步/等待的文章,但是据我了解,它是针对下一个.NET版本的,因此无法使用)?

这肯定是一个非常普遍的问题,但是我不确定要寻找什么?
一个想法是添加一个Dictionary< Int32,Answer>.在Receiver类中,但是如果有一些为此设计的.NET工具,我宁愿使用它们...

任何想法,链接甚至代码示例都值得欢迎.

预先感谢,



also Receiver.onAnswerReceive is going to be called for a lot of answers , the link between the request and the answer is the Int32 uniqueRequestID.

So I have two problems :
1. how do I do to wait for the answer?
2. how to access the Answer from getData method in C# 4.0 ?
(I saw some articles about async/wait but as I understand it''s for the next release of .NET so not usable)?

It must be a pretty common problem but I''m not sure what to look for?
One idea was to add a Dictionary<Int32, Answer> in the Receiver class, but if there are some .NET tools designed for this I would rather use them...

Any idea, link, or even code sample more than welcome.

Thanks in advance,

推荐答案

让我继续我在对该问题的评论中提出的问题.

我认为当线程不是司空见惯的时候,异步API蓬勃发展.这些天来,他们终于失去了目标,除了支持一些遗产.在所有阻塞调用中但在单独的线程中使用纯同步方法要好得多.您主要遵循顺序逻辑,使用通常的线程同步原语和无论如何都需要使用的技术,您将拥有更加清晰得多的控制权.由于这些原因,这样的多线程代码变得更可靠,更易于测试和调试.

—SA
Let me continue from the question I asked in my comment to the question.

I think that asynchronous API flourished when threads were not a commonplace; and these days they finally lost their purposes, except supporting some legacy. Using purely synchronous approaches with all blocking call but in separate threads is much better. You follow mostly sequential logic, you use commonly thread synchronization primitives and techniques you need to use anyway, you have much more of much clearer control. By those reasons, such multithreading code becomes more reliable, easier to test and debug.

—SA


这篇关于调用异步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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