线程上调用带参函数
线程传参步骤:
1、通过实例化委托时来调用工作函数,
工作函数是带参数的;委托也带参数由下面的步骤来传参数
2、通过实例化线程时候调用一个方法,该方法的作用将参数传给委托
实例如下:
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading ;
namespace _03_ThreadDelegate
{
public class SimpleThread
{
//委托变量声明
public delegate void delegateStart(object o);
//一个class
public class Args
{
public object o;
public delegateStart delegateOne;
public void delegateWork() //将参数传到委托上
{
delegateOne (o);
}
}
//创建线程方法
public static Thread CreateThread(delegateStart delegatestart,object arg)
{
Args args = new Args();
args.o = arg;
args.delegateOne = delegatestart;
Thread t = new Thread(new ThreadStart(args.delegateWork));
return t;
}
}
class Worker
{
public static void WorkMathod(object o)
{
Console.WriteLine("参数为:" + o);
}
}
class Program
{
public SimpleThread.delegateStart delegateOne;
static void Main(string[] args)
{
//Thread t = SimpleThread.CreateThread(new SimpleThread.delegateStart(Worker.WorkMathod), "-----我是参数!");
//t.Start();
//t.Join();
//等价于一下代码:
SimpleThread.Args Simple_args = new SimpleThread.Args ();
Simple_args.o = "1";
Simple_args.delegateOne = new SimpleThread.delegateStart(Worker.WorkMathod);//实例化委托,委托中再调用工作函数,来完成工作函数的运行!
Thread t=new Thread (new ThreadStart(Simple_args.delegateWork ));//调用线程,线程上运行一个方法,该方法将参数传进委托方法中
t.Start();
t.Join();
delegateOne("哈哈");
Thread t = new Thread(new ThreadStart());
t.Start();
t.Join();
}
}
}
1、通过实例化委托时来调用工作函数,
工作函数是带参数的;委托也带参数由下面的步骤来传参数
2、通过实例化线程时候调用一个方法,该方法的作用将参数传给委托
实例如下:
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading ;
namespace _03_ThreadDelegate
{
public class SimpleThread
{
//委托变量声明
public delegate void delegateStart(object o);
//一个class
public class Args
{
public object o;
public delegateStart delegateOne;
public void delegateWork() //将参数传到委托上
{
delegateOne (o);
}
}
//创建线程方法
public static Thread CreateThread(delegateStart delegatestart,object arg)
{
Args args = new Args();
args.o = arg;
args.delegateOne = delegatestart;
Thread t = new Thread(new ThreadStart(args.delegateWork));
return t;
}
}
class Worker
{
public static void WorkMathod(object o)
{
Console.WriteLine("参数为:" + o);
}
}
class Program
{
public SimpleThread.delegateStart delegateOne;
static void Main(string[] args)
{
//Thread t = SimpleThread.CreateThread(new SimpleThread.delegateStart(Worker.WorkMathod), "-----我是参数!");
//t.Start();
//t.Join();
//等价于一下代码:
SimpleThread.Args Simple_args = new SimpleThread.Args ();
Simple_args.o = "1";
Simple_args.delegateOne = new SimpleThread.delegateStart(Worker.WorkMathod);//实例化委托,委托中再调用工作函数,来完成工作函数的运行!
Thread t=new Thread (new ThreadStart(Simple_args.delegateWork ));//调用线程,线程上运行一个方法,该方法将参数传进委托方法中
t.Start();
t.Join();
delegateOne("哈哈");
Thread t = new Thread(new ThreadStart());
t.Start();
t.Join();
}
}
}