关于使用任务队列ConcurrentQueue完成图像上传的一个案例

情景:需要在图像处理完成后,上传到云端

思路:在图像处理完成后,将图像任务加入上传的任务队列,异步上传。

类:ImageUploadServices

在主界面的合适位置初始,得到ImageUploadServices的单例服务,在执行图像处理任务前,初始化上传服务的任务队列(Task_Init),当

ConcurrentQueue中任务数量不为0时,执行任务。后续只需要在每张图像处理完毕的时候作为任务加到任务队列中:
Tasks_Add(ImageFile data)
ublic class ImageUploadServices
    {
        /// <summary>
        /// 初始化
        /// </summary>
        private static ImageUploadServices _instance;

        private int imgag_id = 0;

        public static ConcurrentQueue<ImageFile> ImaeUpload_File = new ConcurrentQueue<ImageFile>();

        public enum AnscardUplodaState
        {  
            [Display(Name = "待上传")]
            WaitToUpload = 0,

            [Display(Name = "正在上传")]
            Uploading = 1,

            [Display(Name = "上传成功")]
            UploadSuccess = 2,

            [Display(Name = "上传失败")]
            UploadFailed = 3,
        }

        private static int Tasks_Count;
        private int _tasks_state = 0;
        Form parent;
        private DateTime Tasks_Time;

        public Thread Tasks_Thread;

        public int Tasks_State
        {
            get
            {
                return _tasks_state;
            }
            set
            {
                _tasks_state = value;
                if (value == 0)
                {
                    Tasks_Timer();
                }
            }
        }

        public static ImageUploadServices GetInstance(Form parent)
        {
            return _instance ?? (_instance = new ImageUploadServices(parent));
        }

        public ImageUploadServices(Form parent)
        {
            _instance = new ImageUploadServices();
            parent = parent;
        }
        private ImageUploadServices()
        {
        }

        public void Tasks_Init(int imgag_id)
        {
            this.imgag_id = imgag_id;
            ImaeUpload_File = new ConcurrentQueue<ImageFile>();
            Tasks_Count = 0;

            Tasks_State = task_state;
            Tasks_Thread = new Thread(Tasks_Run);
            Tasks_Time = DateTime.Now;
        }

        /// <summary>
        /// 时间统计
        /// </summary>
        private void Tasks_Timer()
        {

        }

        private void Tasks_Run()
        {
            //设置最大任务数量
            int Tasks_Count_Max = 2;

            while ((ImaeUpload_File != null && ImaeUpload_File.Count > 0) || Tasks_State > 0)
            {
                if (ImaeUpload_File != null && ImaeUpload_File.Count > 0 && Tasks_Count < Tasks_Count_Max)
                {
                    ImageFile file = null;
                    bool isSuc = ImaeUpload_File.TryDequeue(out file); 
                    if (isSuc)
                    {
                        Tasks_Do(file);
                        // Task.Run(() => Tasks_Do(file));
                        Tasks_Count++;
                    }
                    Thread.Sleep(100);
                }
                else
                {
                    Thread.Sleep(1000);
                }
            }
        }

        private async Task Tasks_Do(ImageFile data)
        {
            await Task.Run(() =>
            {
                try
                {
                    //if (string.IsNullOrEmpty(RestfulServiceClient.Token))
                    //{
                    //    MessageBox.Show("远程服务端身份验证失败!");
                    //    Tasks_Count--;
                    //    return;
                    //}

                    string imgCosPath = "";
                    if (!String.IsNullOrEmpty(data.firstPage))
                    {
                        string cosPath = String.Format("GctAnalyse/AnswerSheet/{0}.png",data.studentCode);
                        if (File.Exists(data.firstPage) && data.isUpload == 0)
                        {
                            string newUrl = CosossService.CreateOssService().SyncUploadFile(answerSheetCosPath, data.firstPage);
                            imgCosPath = newUrl;
                        }
                    }

                    if(!String.IsNullOrEmpty(imgCosPath))
                    {
                        parent.updateImgUploadState(data, AnscardUplodaState.UploadSuccess);
                        data.isUpload = 1;
                    }
                    else
                        parent.updateImgUploadState(data, AnscardUplodaState.UploadFailed);
                }
                catch (Exception ex)
                {
                    Utils._log.Error("执行异常" + "文件ID" + data.ID + "任务ID" + ",异常" + ex);
                }
                finally
                {
                    Tasks_Count--;
                }
            });
        }

        /// <summary> 
        /// 添加扫描的记录
        /// </summary>
        /// <param name="data"></param>
        public void Tasks_Add(ImageFile data)
        {
            if (data != null)
            {
                ImaeUpload_File.Enqueue(data);
            }
        }
    }
}

 

 

posted @ 2025-07-09 17:41  Wind_Swing_Dunn  阅读(11)  评论(0)    收藏  举报