Unity C# 中Async await 的几种使用方式

这篇博客介绍了Unity中使用Async-Await进行异步操作的各种场景,包括异步文件拷贝、延时等待、委托等待、条件暂停以及异步读取文件等。示例代码展示了如何有效地利用异步编程提高程序效率,避免阻塞主线程。
摘要由CSDN通过智能技术生成

Unity中 Async - await 的 几种实用场景


//Asyn 常用方法
public class AsynFun
{
    public void Main()
    {
        TryGetUnittOnLocal("sss");
       // OnRunStarted = OnRunStarted2;
    }

	//返回上级目录。leave设置级数
	string UpDirectory(string path,int leave)
    {
        string destPath = Path.GetFullPath(path);
        for (int i = 0; i < leave; i++)
        {
                Directory.SetCurrentDirectory(Directory.GetParent(destPath).FullName);
                destPath = Directory.GetCurrentDirectory();
        }
        return destPath;
     }
	
	// 异步拷贝文件
     async Task CopyToAndriodRoot()
     {
        string orginPath = Path.Combine(Application.persistentDataPath, "test.txt");

        string destNewPath = UpDirectory(Application.persistentDataPath, 3); 

        if (!Directory.Exists(destNewPath))
        {
                Debug.Log("没有这个文件夹路径 :" + destNewPath);
        }
        else
        {
                destNewPath = Path.Combine(destNewPath, "test.txt");

                if (File.Exists(orginPath))
                {
                    await Task.Run(() => {

                        File.Copy(orginPath, destNewPath,true);

                    });
                }
                else
                {
                    Debug.Log("没有这个文件 :" + orginPath + "\n" + "新文件夹 :" + destNewPath);
                }
        }

          
    }
        
    /// <summary>
    /// 延时等待
    /// </summary>
    public async void Delay()
    {
        await Task.Delay(2000);

        //操作//
    }
    /// <summary>
    /// 延时三针再操作
    /// </summary>
    public async void DelaySet()
    {
        await Task.Yield();
        await Task.Yield();
        await Task.Yield();

        //操作//
    }


    Func<Task> OnRunStarted;
    /// <summary>
    /// 等待一个委托方法有返回之后再运行
    /// </summary>
    public async void WaitFun()
    {
        await OnRunStarted?.Invoke();
        //操作//
    }

    async Task OnRunStarted2()
    {

    }

    /// <summary>
    /// 通过BOOL判断,来暂停现成
    /// </summary>
    public async void BoolPause()
    {
        bool isRun = false;
        while (!isRun)
        {
            await Task.Yield();
        }

        //操作//
    }


    /// <summary>
    /// 返回一个已经完成的Task对象【未测试】
    /// </summary>
    /// <returns></returns>
    public Task ReturnCompletedTask()
    {
        return Task.CompletedTask;
    }

    /// <summary>
    /// 返回值为Task
    /// </summary>
    public async Task<Dictionary<int,string>> RetureTask()
    {
        return await Task.Run(()=> {
            return new Dictionary<int, string>();
        });

        //操作//
    }


    /// <summary>
    /// 异步读取文本文件【写入同样这样】
    /// </summary>
    /// <param name="filePath"></param>
    public async void TryGetUnittOnLocal(string filePath)
    {
        try
        {
           // string unitJson = await Task.Run(() => File.ReadAllText(filePath));

            Task<string> task = Task.Run(() => File.ReadAllText(filePath));
            await task;
            string unitJson = task.Result;

            //List<string> dd = new List<string>();
            //dd.Where(str => str =="d").ToList();
        }
        catch (Exception ex)
        {
            Debug.LogWarning(ex);
        }
    }
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值