c#线程基本知识+多线程技术用于大量计算方面

unity 13章 多线程技术与网络开发

13.1.1开启线程

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Threading;

public class NewBehaviourScript : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        Thread thread = new Thread(run);
        thread.Start();
    }

    // Update is called once per frame
    void Update()
    {
                                                            
    }

    void run()
    {
        Debug.Log("开启线程");
    }
}

13.1.2加锁(同一时刻只能被一个线程访问或者修改)

获取锁才能操作数据,操作数据后释放数据

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Threading;

public class NewBehaviourScript : MonoBehaviour
{
    public static Object o = new Object();
    public int n = 0;
    void Start()
    {
        Thread thre
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当我们需要在 C# WinForm 应用程序中执行耗时的任务时,我们可以使用多线程来避免 UI 假死的情况。下面是一些多线程的学习知识和具体实例: 1. 创建线程 使用 System.Threading 命名空间中的 Thread 类来创建新线程。以下是创建新线程的示例: ```C# Thread newThread = new Thread(new ThreadStart(MyMethod)); newThread.Start(); ``` 2. 使用委托更新 UI 在多线程环境下,只有创建 UI 控件的主线程才能访问和更新 UI 控件。如果需要在其他线程中更新 UI 控件,可以使用委托来实现。以下是一个使用委托更新 UI 的示例: ```C# private delegate void UpdateTextBoxDelegate(string text); private void UpdateTextBox(string text) { if (textBox1.InvokeRequired) { UpdateTextBoxDelegate updateDelegate = new UpdateTextBoxDelegate(UpdateTextBox); textBox1.Invoke(updateDelegate, new object[] { text }); } else { textBox1.Text = text; } } ``` 3. 使用线程线程池是一组可重用的线程,可以用来执行多个短时间的任务。使用线程池可以避免创建和销毁线程的开销。以下是一个使用线程池的示例: ```C# ThreadPool.QueueUserWorkItem(new WaitCallback(MyMethod)); ``` 4. 取消线程 如果需要取消正在运行的线程,可以使用 CancellationToken 类来实现。以下是一个取消线程的示例: ```C# private CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); private void MyMethod(CancellationToken cancellationToken) { while (true) { if (cancellationToken.IsCancellationRequested) { break; } // Do some work... } } private void button1_Click(object sender, EventArgs e) { cancellationTokenSource.Cancel(); } ``` 以上是一些多线程的学习知识和具体实例,希望对你有所帮助。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值