如果可能的话,我希望通过目标变量获取传递给方法的值(即#34; Hello world")。我查看并测试了它的所有属性,但它们公开了参数的名称,但没有公开它的值,正如我所看到的那样。谢谢
using System;
using System.Threading;
class ThreadTest
{
static void Main()
{
IAsyncResult output;
Func<string, int> method = Worker;
output = method.BeginInvoke("Hello world!", Done, method);
Console.ReadLine();
}
static void Done(IAsyncResult cookie)
{
var target = (Func<string, int>)cookie.AsyncState;
int result = target.EndInvoke(cookie);
Console.WriteLine("String length is " + result);
}
static int Worker(string s)
{
return s.Length;
}
}
答案 0 :(得分:0)
IAsyncState
不存储输入参数。因此,您无法直接使用此机制来检索委托的参数。
但是你有两种方法来检索这个论点。
ref
参数@object
参数中的参数以便稍后检索用例#1的示例
delegate int Foo(ref string arg);
static void Main() {
Foo method = Worker;
var arg1 = "Hello world!";
var output = method.BeginInvoke(ref arg1, Done, method);
Console.ReadLine();
}
static void Done(IAsyncResult cookie) {
var target = (Foo)cookie.AsyncState;
string arg1 = "";
int result = target.EndInvoke(ref arg1, cookie);
Console.WriteLine("String length is " + result);
Console.WriteLine("Passed argument was " + arg1);
}
static int Worker(ref string s) {
return s.Length;
}
注意我使用Foo
参数而不是ref string
的{{1}}
案例#2的例子:
Func
注意我是如何传递static void Main() {
Func<string, int> method = Worker;
var arg1 = "Hello world!";
var output = method.BeginInvoke(arg1, Done, Tuple.Create(method, arg1));
Console.ReadLine();
}
static void Done(IAsyncResult cookie) {
var target = (Tuple<Func<string, int>, string>)cookie.AsyncState;
int result = target.Item1.EndInvoke(cookie);
Console.WriteLine("String length is " + result);
Console.WriteLine("Passed argument was " + target.Item2);
}
static int Worker(string s) {
return s.Length;
}
来保存原始委托和论坛的参数。