多线程学习1(20131001)

来源:互联网 发布:编程自学 编辑:程序博客网 时间:2024/04/28 21:23

1、委托、匿名方法、lambda表达式:

定义委托:public delegate int MyDel(int a, int b);

声明委托:MyDel myDel = delegate(int a, int b) { return a + b; };

    MyDel myDel = (int a, int b)=> { return a + b; };

                    MyDel myDel = (a, b) => a + b; 

2、扩展方法:

1)模拟实现List的FindAll方法。

声明部分:List<string> list = new List<string>() { "2", "4", "5", "7" };

添加一个类写入:

 public delegate bool IsOk<T>(T obj);
    public static class AddListFunction
    {
        public static List<T> MyList<T>(this List<T> list, IsOk<T> del)
        {
            List<T> result = new List<T>();
            foreach (var item in list)
            {
                if (del(item))
                {
                    result.Add(item);
                }
            }
            return result;
        }
    }

调用部分:List<string> myList = list.MyList(listI => int.Parse(listI) > 4);

2)Func有返回值,用法举例:

    Func<int, bool> del = num1 => num1 > 2;
            List<int> list=new List<int>(){1,2,3,5,6};
            IEnumerable<int> myList = list.Where(del);

3)Action无返回值,用法举例:

            Action<int, int> action = (a, b) => Console.WriteLine(a + b);
            action(1,1);

3、进程:

Process process = Process.Start(@"D:\Program Files\kuwo\KWMUSIC2013\KwMusic.exe","海阔天空");

获取本机运行中的进程:Process[] p = Process.GetProcesses();

自己的进程:Process p1 = Process.GetCurrentProcess();

关闭进程:p1.Kill(); 

4、应用程序域:

示例代码:

    AppDomainSetup appDomainSetup = new AppDomainSetup();
            appDomainSetup.LoaderOptimization = LoaderOptimization.SingleDomain;
            AppDomain appDomain = AppDomain.CreateDomain("MyAppDomain",null,appDomainSetup);
            appDomain.ExecuteAssembly("WindowsFormsApplication1.exe");

运行另一个exe文件,与主应用程序域无关。

5、线程:

//获取当前线程。
            Thread mainThread = Thread.CurrentThread;

//创建一个线程:

Thread thread = new Thread(Do);

//启动线程:

thread.Start();

//设置后台线程:

thread.IsBackground = true;

//线程ID;

Thread.CurrentThread.ManagedThreadId

//关闭线程:

thread.Abort();

//线程级别:

thread.Priority = ThreadPriority.Highest;

//带参数的线程:

   Thread thread = new Thread(a =>
            {
                Console.WriteLine(a);
            });
            thread.Start("Hello World");

6、异步委托:

MyDelAdd mda = new MyDelAdd(Add);

IAsyncResult ascResult = mda.BeginInvoke(1, 2, new AsyncCallback(MyDelCallBack), 0);

回调函数:

public static void MyDelCallBack(IAsyncResult result)
        {
            AsyncResult aReuslt = (AsyncResult)result;
            MyDelAdd del = (MyDelAdd)aReuslt.AsyncDelegate;
            int addResult = del.EndInvoke(result);
            int state = (int)aReuslt.AsyncState;
            Console.WriteLine("异步执行的结果是:{0}", addResult);
        }

7、多线程摇奖机:

namespace 摇奖机
{
    public partial class Form1 : Form
    {
        List<Label> list = new List<Label>();
        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }
        bool IsStart = false;
        private void button1_Click(object sender, EventArgs e)
        {
            IsStart = true;
            new Thread(() =>
            {
                Random ran = new Random();
                while (IsStart)
                {
                    for (int i = 0; i < 3; i++)
                    {
                        list[i].Text = ran.Next(0, 10).ToString();
                    }
                    Thread.Sleep(10);
                }
            }).Start();
        }
        private void button2_Click(object sender, EventArgs e)
        {
            IsStart = false;
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            for (int i = 0; i < 3; i++)
            {
                Label label = new Label();
                label.Text = "0";
                label.AutoSize = true;
                label.Location = new Point(50 * i + 150, 100);
                list.Add(label);
                this.Controls.Add(label);
            }
        }
    }
}

8、锁、死锁:

lock(引用类型)。

死锁:相互等待对方释放资源。减少死锁现象:操作资源的顺序要一致。

9、线程池

ThreadPool.QueueUserWorkItem(new WaitCallback(ShowMsg), "Hello");

//工作项执行的顺序不确定。推荐使用可提高性能。

10、工作项:解决有返回值的问题。

Task<T> task=new Task<string>(委托);

task.Result即返回值。

11、并行计算:

Parallel.For();

并行计算就不去深入了解啦,太深奥了。



原创粉丝点击