Unity C#异步读取

简单封装了一下,下次再用的时候直接拿取用,不用每次都手写一遍了

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

public class AsyncIOTask
{
    public async Task<byte[]> Read(string path)
    {
        using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            stream.Seek(0, SeekOrigin.Begin);
            byte[] bytes = new byte[stream.Length];
            if (stream.Length < int.MaxValue)
            {
                await stream.ReadAsync(bytes, 0, (int)stream.Length);
            }
            return bytes;
        }
    }
    public async Task Read(string path, Action<byte[]> finish)
    {
        using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            stream.Seek(0, SeekOrigin.Begin);
            byte[] bytes = new byte[stream.Length];
            if (stream.Length < int.MaxValue)
            {
                await stream.ReadAsync(bytes, 0, (int)stream.Length);
            }
            finish?.Invoke(bytes);
        }
    }
    /// <summary>
    /// 执行起来似乎比上面的public async Task Read(string path, Action<byte[]> finish)快的多
    /// </summary>
    public Task TaskRunRead(string path, Action<byte[]> finish)
    {
        return Task.Run(() => {
            using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                stream.Seek(0, SeekOrigin.Begin);
                byte[] bytes = new byte[stream.Length];
                if (stream.Length < int.MaxValue)
                {
                    stream.Read(bytes, 0, (int)stream.Length);
                }
                finish?.Invoke(bytes);
            }
        });
    }

    public async Task<byte[]> Read(FileStream stream)
    {
        stream.Seek(0, SeekOrigin.Begin);
        byte[] bytes = new byte[stream.Length];
        if (stream.Length < int.MaxValue)
        {
            await stream.ReadAsync(bytes, 0, (int)stream.Length);
        }
        return bytes;
    }
    public async Task Read(FileStream stream, Action<byte[]> finish)
    {
        stream.Seek(0, SeekOrigin.Begin);
        byte[] bytes = new byte[stream.Length];
        if (stream.Length < int.MaxValue)
        {
            await stream.ReadAsync(bytes, 0, (int)stream.Length);
        }
        finish?.Invoke(bytes);
    }


    public async Task Write(string path, byte[] buffer)
    {
        using (FileStream stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
        {
            await stream.WriteAsync(buffer, 0, buffer.Length);
        }
    }
}

 

这样调用

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

public class NewBehaviourScript : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        System.DateTime time = System.DateTime.Now;
        AsyncIOTask asyncIOTask = new AsyncIOTask();

        List<Task> task1 = new List<Task>();
        List<Task> task2 = new List<Task>();
        for (int i = 0; i < 200; i++)
        {
            int index = i;
            string readPath = @"E:\Temp\2\" + index.ToString() + ".jpg";

            Task t1 = asyncIOTask.Read(readPath, async (a) =>
            {
                await asyncIOTask.Write(@"E:\Temp\2\" + index.ToString() + "_async_io.jpg", a);
            });
            task1.Add(t1);

            Task t2 = asyncIOTask.TaskRunRead(readPath, async (a) =>
            {
                await asyncIOTask.Write(@"E:\Temp\2\" + index.ToString() + "_async_work.jpg", a);
            });
            task2.Add(t2);
        }
        Task.WhenAll(task1).ContinueWith((a)=> { Debug.LogError((System.DateTime.Now - time).TotalMilliseconds.ToString() + "___task io"); });//耗时18688.5558毫秒
        Task.WhenAll(task2).ContinueWith((a)=> { Debug.LogError((System.DateTime.Now - time).TotalMilliseconds.ToString() + "___task work"); });//耗时5378.5248毫秒
    }

}

 

posted on 2022-08-23 14:49  Jason_c  阅读(425)  评论(1)    收藏  举报