Unity中 Async - await 的 几种实用场景
public class AsynFun
{
public void Main()
{
TryGetUnittOnLocal("sss");
}
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);
}
}
}
public async void Delay()
{
await Task.Delay(2000);
}
public async void DelaySet()
{
await Task.Yield();
await Task.Yield();
await Task.Yield();
}
Func<Task> OnRunStarted;
public async void WaitFun()
{
await OnRunStarted?.Invoke();
}
async Task OnRunStarted2()
{
}
public async void BoolPause()
{
bool isRun = false;
while (!isRun)
{
await Task.Yield();
}
}
public Task ReturnCompletedTask()
{
return Task.CompletedTask;
}
public async Task<Dictionary<int,string>> RetureTask()
{
return await Task.Run(()=> {
return new Dictionary<int, string>();
});
}
public async void TryGetUnittOnLocal(string filePath)
{
try
{
Task<string> task = Task.Run(() => File.ReadAllText(filePath));
await task;
string unitJson = task.Result;
}
catch (Exception ex)
{
Debug.LogWarning(ex);
}
}