C#之线程

线程,通俗的讲是指程序在一个时间点内处理事物的能力,多线程,指程序能够同一时间点处理多种事物。

C#中的线程使用于System.Threading命名空间下。

一.通过Thread类创建线程:

支持无参函数和参数为object类型的函数。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace ThreadTest
{
    class Person
    {
        public Person ()
        {
            Thread t = new Thread(Speak);
            t.Start();
        }

        private void Speak ()
        {
            Console.WriteLine("Person speak");
        }
    }
}

参数为object类型的函数:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace ThreadTest
{
    class Person
    {
        public Person()
        {
            Thread t = new Thread(Speak);
            t.Start("haha");
        }

        private void Speak(object aa)
        {
            Console.WriteLine(aa);
        }
    }
}

那么,如何通过Thread创建能传递多个参数的线程呢?

1.封装函数结构:

新建CustomThread类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace ThreadTest
{
    class CustomThread
    {
        private string paramStr;
        private int paramInt;

        public CustomThread (string paramStr, int paramInt)
        {
            this.paramStr = paramStr;
            this.paramInt = paramInt;
            Thread t = new Thread(Work);
            t.Start();
        }

        private void Work ()
        {
            Console.WriteLine("paramStr:" + paramStr + " paramInt:" + paramInt);
        }
    }
}

这样封装一下Thread,把需要的参数通过构造函数存到CustomThread中,达到实例化多参数线程的目的。

2.使用委托:

通过委托的BeginInvoke可以开启一个后台委托,接受一个回调函数,并在EndInvoke中返回函数返回值,代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace ThreadTest
{
    class Person
    {
        Func<int, int> func;
        public Person()
        {
            func = Cal;
            func.BeginInvoke(1, args => {
                int result = func.EndInvoke(args);
                Console.WriteLine("结果为: " + result);
            }, null);
        }

        private int Cal (int num)
        {
            Thread.Sleep(2000);
            return num + 1;
        }
    }
}

注意,这里主线程如果执行结束,这个后台委托也会被停止!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值