Reputation: 527
I'm relatively new to 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:
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.
What's the best way to return a value like this?
Upvotes: 0
Views: 476
Reputation: 527
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.
Upvotes: 0
Reputation: 550
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'.
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
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.
Upvotes: 1