AsyncCallback getting values through reference variable
I need to call a function using asynchronous delegates, when i go through the tutorial of the AsyncCallback I saw the async call back defined as below:
static void CallbackMethod(IAsyncResult result)
{
// get the delegate that was used to call that
// method
CacheFlusher flusher = (CacheFlusher) result.AsyncState;
// get the return value from that method call
int returnValue = flusher.EndInvoke(result);
Console.WriteLine("The result was " + returnValue);
}
Please let me know if i can get the return value as reference from the function. eg:= my function is in the format
void GetName(int id,ref string Name);
Here i am getting the output from the function through a reference variable. If i call this开发者_运维技巧 function using the async delegates how can i read the output from the callback function?
You need to wrap your arguments into an object:
class User
{
public int Id { get; set; }
public string Name { get; set; }
}
void GetName(IAsyncResult result)
{
var user = (User)result.AsyncState
// ...
}
AsyncCallback callBack = new AsyncCallback(GetName);
Don't pass the return value back via a ref
parameter. Instead, change the signature to:
string GetName(int id)
or possibly:
string GetName(int id, string defaultName) // Or whatever
Note that there's a big difference between "a reference" and "pass-by-reference". It's important to understand the distinction.
精彩评论