无返回值 带参数和不带参数委托传递给线程
using System;
using System.Threading;
using System.Threading.Tasks;
namespace threadDelegate
{
class Program
{
static void Main(string[] args)
{
//ThreadStart这个类参数是个委托,委托里面只有返回void,同时该委托没有参数,method方法中的参数去掉不能添加参数
Delegate1 dt = new Delegate1();
Thread T1 = new Thread(new ThreadStart(dt.func1));//传递非静态委托
T1.Start();
Thread T2 = new Thread(new ThreadStart(Delegate2.func2));传递静态委托
T2.Start();
Delegate3 dt3 = new Delegate3();
String hello = "hello";
// //如果写成Thread thread = new Thread(ThreadMainWithParameters(hello));这种形式,编译时就会报错
Thread T3 = new Thread(()=> dt3.func3(hello));//Lambda表达式不用进行类型转换
T3.Start();
//这里也可简写成Thread thread = new Thread(ThreadMainWithParameters);
//但是为了让大家知道这里用的是ParameterizedThreadStart委托,就没有简写了
Thread T4 = new Thread(new ParameterizedThreadStart(Delegate4.func4));
//hreadMainWithParameters方法里的参数必须是object类型的,我们需要进行类型转换。
T4.Start(hello);
T4.Join();
String hello1 = "hello ha";
Thread T5 = new Thread(Delegate4.func4);
T5.Start(hello1);
}
}
class Delegate1{
public void func1()
{
Console.WriteLine("Delegate1");
}
}
class Delegate2
{
public static void func2()
{
Console.WriteLine("Delegate2");
}
}
class Delegate3
{
public void func3(string obj)
{
Console.WriteLine("Delegate3:{0}", obj);
}
}
class Delegate4
{
public static void func4(Object obj)
{
Console.WriteLine("Delegate4:{0}", obj);
}
}
}
任务
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ThreadTest
{
class Program
{
static void Main(string[] args)
{
//泛型委托
Task<int> task2 = new Task<int>(count);
task2.Start();
Task task3 = task2.ContinueWith(print);//在一个任务执行完之后接着执行ContinueWith里面的任务
print(task2);
task2.Wait();
}
//这里传递进去的线程参数类型只能是Object类型否则报错
public static void print(Task<int> task) {
Console.WriteLine("再打印出来:"+task.Result);
}
static int count()
{
int result = 0;
for (int i = 0; i < 10000; i++)
{
result += i;
}
Console.WriteLine("先计算count");
return result;
}
}
}