Several ways to use Async await in Unity C#

Several practical scenarios of Async-await in Unity


//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);
        }
    }

Guess you like

Origin blog.csdn.net/KiTok/article/details/123669019
Recommended