参考网址【https://www.cnblogs.com/pnljs/p/3792407.html】
示例代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApp3
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Loaded += MainWindow_Loaded;
}
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
//Testc(); //无返回值
Main(); //有返回值
}
private void Testc()
{
int a = 0;
while (true)
{
string ip = "192.168.127." + (a++);
Func<string, int, bool> func = new Func<string, int, bool>(Clearing);
IAsyncResult asyncResult = func.BeginInvoke(ip, a, o =>
{
var h = func.EndInvoke(o);
}, func);
//bool res = func.EndInvoke(asyncResult);
//Console.WriteLine("第{0}次返回字符串是{1}", asyncResult.AsyncState.ToString(), res);
/*
return;
ThreadPool.QueueUserWorkItem((v) => {
string ip = "192.168.127." + (a++);
Func<string, int, bool> func = new Func<string, int, bool>(Clearing);
IAsyncResult asyncResult = func.BeginInvoke(ip, a, o =>
{
var h = func.EndInvoke(o);
}, func);
//bool res = func.EndInvoke(asyncResult);
//Console.WriteLine("第{0}次返回字符串是{1}", asyncResult.AsyncState.ToString(), res);
});
*/
//object obj = asyncResult.AsyncState;
Thread.Sleep(500);
break;
}
Console.WriteLine(DateTime.Now);
}
private bool Clearing(string ipAddress,int a)
{
bool result = false;
while (true)
{
try
{
Console.WriteLine("a:" + a);
Console.WriteLine(ipAddress);
}
catch (Exception err)
{
}
Thread.Sleep(1000);
//break;
}
return result;
}
public void printa(){}
private void Main()
{
Func<int, string> fun = new Func<int, string>(A);
IAsyncResult asyncResult = fun.BeginInvoke(4, o =>
{
var h = fun.EndInvoke(o);
}, fun);
while (!asyncResult.IsCompleted)
{
Console.WriteLine("正在执行中……");
}
Console.WriteLine(DateTime.Now);
}
//private void Res(IAsyncResult ar)
//{
// //Func<int,string> func = (Func<int, string>)ar;
//
// Func<int, string> caller = ar.AsyncState as Func<int, string>;
// string d = caller.EndInvoke(ar);
//
// //AsyncMethodCaller caller = (AsyncMethodCaller)ar.AsyncDelegate;
//
// //string returnValue = caller.EndInvoke(out threadId, ar) ;
// //Console.WriteLine("The call executed on thread {0}, with return value \ "{ 1}\ ". ", threadId, returnValue);
//
//
//}
private string A(int d)
{
Thread.Sleep(5000);
return "fdsfasfadsfsadfas";
}
}
}