高人高人你在哪儿?
简单点儿说:这是个控制台应用程序,现在有这样两个函数
public int main()
{
int temp = 1;
int result = 0;
result = test(temp);
Console.WriteLine("I wanna call it frist");
return result;
}public int test(int param)
{
System.Threading.Thread.Sleep(2000);
Console.WriteLine("{0}",result);
return ++param;
}
正常情况下应该显示2,I wanna call it frist;现在我想把对test这个函数的调用变成异步的,也就是让结果显示出I wanna call it frist,2。注意,主函数里需要用到test函数的返回值的。麻烦高手帮忙改一下。不用注重格式,能说明意思就行。如果能稍做注释,感激不尽。
简单点儿说:这是个控制台应用程序,现在有这样两个函数
public int main()
{
int temp = 1;
int result = 0;
result = test(temp);
Console.WriteLine("I wanna call it frist");
return result;
}public int test(int param)
{
System.Threading.Thread.Sleep(2000);
Console.WriteLine("{0}",result);
return ++param;
}
正常情况下应该显示2,I wanna call it frist;现在我想把对test这个函数的调用变成异步的,也就是让结果显示出I wanna call it frist,2。注意,主函数里需要用到test函数的返回值的。麻烦高手帮忙改一下。不用注重格式,能说明意思就行。如果能稍做注释,感激不尽。
{
System.Threading.Thread.Sleep(2000);
Console.WriteLine("{0}", 2);
} public static void Main()
{
(new Thread(new ThreadStart(test))).Start();
Console.WriteLine("{0}", 1);
}
EndInvoke是阻塞当前主线程,直到这个异步执行的方法完成为止
举个例子MyDelegate myDelegate = GetStringFromOtherComputer;
IAsyncResult result = myDelegate.BeginInvoke(null,null);//从别的计算机获取一些数据
DoOther();//做一些其它的事情,以提高效率;
String data = myDelegate.EndInvoke(result,null,null);//必须这个数据完成后,才能开始下边的操作;这个时候主线程是阻塞的。
Console.Write(data);
String[] localIps = ConfigurationManager.AppSettings["LocalIP"].Split(',');
AttackIPGetterDelegate getterDelegate = new AttackIPGetter(localIps).Get;
IAsyncResult getResult = getterDelegate.BeginInvoke(null, null);
KilledIps killedIps = new KilledIps();
killedIps.AddSafeIps(GetDaDiIPs());
killedIps.RemoveExpiredIps();
killedIps.RemoveSafeIps(); List<IP> ips = getterDelegate.EndInvoke(getResult);