简体   繁体   English

C#从回调函数返回异步参数

[英]C# returning asynchronous parameter from callback function

I'm relatively new to C#. 我是C#的新手。 I'm having some troubles returning values from a callback. 我在从回调返回值时遇到了一些麻烦。 I've got a struct like: 我有一个像这样的结构:

struct Params
{
  ...
  XXX[] xxx;
}

and a callback function that gets called whenever some XXX data is ready: 和一个回调函数,只要准备好一些XXX数据,就会调用该回调函数:

void Callback(object response, object param)
{
  var data = (Params)param;
  data.xxx = (XXX[])response;
  // signal
}

Which is used like: 用法如下:

Param param = new Param();
...
MakeRequest(Callback, param);
...

Inside Callback data.xxx has the correct value, however (after I get a signal that the data is ready) whatever I pass trough "param" to Callback has the xxx member set to null. 在Callback内部,data.xxx具有正确的值,但是(在我收到数据准备就绪的信号之后),无论我如何通过“参数”通过Callback将xxx成员设置为null。

What's the best way to return a value like this? 返回这样的值的最佳方法是什么?

You have declared your 'data' variable inside the scope of the callback. 您已在回调范围内声明了“数据”变量。 Callbacks, in most cases, are not invoked in the same thread they were called from (In many platforms, not just .NET) so the CLR might not guarantee the value of a local inside 'callback'. 在大多数情况下,回调不会在从其调用的同一线程中调用(在许多平台中,不仅是.NET),因此CLR可能无法保证“回调”内部的本地值。

What you may do, provided you can change the signature of the callback, is to make it static, and so for the data variable - also static. 只要可以更改回调的签名,您可以做的是使它变为静态,因此对于数据变量-也是静态的。 A good example for this may be found on the MSDN in the following link: https://msdn.microsoft.com/en-us/library/bbx2eya8(v=vs.110).aspx 在以下链接的MSDN上可以找到一个很好的例子: https : //msdn.microsoft.com/en-us/library/bbx2eya8(v=vs.110).aspx

you don't need to read the whole long article - just roll down to the bottom - see there a callback named: "private static void ReceiveCallback( IAsyncResult ar )" and refer to the variable "receiveDone" in it, which is assumed as static. 您无需阅读整篇长篇文章-滚动至底部-看到一个名为“ private static void ReceiveCallback(IAsyncResult ar)”的回调,并在其中引用了变量“ receiveDone”(假定为静态的。

I think something like... 我觉得像...

class Container
{
  public object container;
}

struct Params
{
  ...
  Container xxx;
}

Params params = new Params();
params.xxx = new Container();

void Callback(object response, object param)
{
  var data = (Params)param;
  data.xxx.container = (XXX[])response;
  // signal
}

...solves it. ...解决它。 Comments? 评论?

EDIT: Realized that's just a passtrough. 编辑:意识到那只是一个通过。 The real code does something with the result. 真正的代码对结果有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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