异步执行例子
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Runtime.Remoting.Messaging;
namespace ConApp
{
class Program
{
private delegate void OutputName();
[STAThread]
public static void Main(string[] args)
{
Test test = new Test();
test.Name = "成功了";
OutputName on = new OutputName(test.TestMethod);
on();//不采用异步的方式
AsyncResult myResult = (AsyncResult)on.BeginInvoke(null, null);//采用异步的方式
while (!myResult.IsCompleted) //判断线程是否执行完成
{
Console.WriteLine("正在异步执行 .....");
}
Console.WriteLine("结束了!");
Thread.Sleep(1000);
}
}
public class Test
{
private string name = "";
public string Name
{
get { return name; }
set { name = value; }
}
public void TestMethod()
{
Console.WriteLine(Name);
Thread.Sleep(5000);
}
}
}
通常给异步执行的方法传参数时采用类和属性的方式。
浙公网安备 33010602011771号