The writing style of Java thread pool is rewritten into the writing style of C# thread pool.

  java, question

The thread pool part of the following C# code is still written in Java. Please ask Dashimen to change it to C#.
Sample code, final code and so on are all very Welcome!

clipboard.png

clipboard.png

clipboard.png

clipboard.png

/// <summary>
        /// 用户初始化ak和sk,sdk自己生成token </summary>
        /// <param name="bucketName"> </param>
        /// <param name="fileKey"> </param>
        /// <param name="randomFile"> </param>
        /// <param name="putPolicy"> </param>
        /// <param name="putExtra"> </param>
        /// <param name="jsonObjectRet"> </param>
        public virtual void execUpload(string bucketName, string fileKey, string randomFile, PutPolicy putPolicy, PutExtra putExtra, JSONObjectRet jsonObjectRet)
        {
            FileInfo randomFileInfo = null;
            ExecutorService pool = null;
            HttpClient mkfileHttpClient = null;
            int retry = 0;
            while (retry < 3)
            {
                string uploadBatch = "SDK-" 加 Guid.NewGuid();// UUID.randomUUID();
                retry加加;
                try
                {
                    if (BaseBlockUtil.BLOCK_SIZE < 4 * BaseBlockUtil.MB || (BaseBlockUtil.BLOCK_SIZE 百分比 4 * BaseBlockUtil.MB) != 0)
                    {
                        jsonObjectRet.onFailure(new Exception("块大小应该为4M的整数倍!"));
                        return;
                    }
                    randomFileInfo = new FileInfo(randomFile);
                    pool = Executors.newFixedThreadPool(BaseBlockUtil.THREAD_NUN);
                    CompletionService<BlockObject> completionService = new ExecutorCompletionService<BlockObject>(pool);
                    if (putExtra.processes == null || putExtra.totalSize != randomFileInfo.Length)
                    {
                        initPutExtra(bucketName, fileKey, randomFile, putExtra, jsonObjectRet);
                    }
                    putExtra.totalSize = randomFileInfo.Length;
                    putPolicy.deadline = Convert.ToString(DateUtil.ToJavaMilliseconds(DateUtil.nextNHours(1, DateTime.Now)));
                    DateTime dealEndDate = DateUtil.nextNMinutes(5, DateTime.Now);
                    string token = TokenUtil.getUploadToken(putPolicy);

                    int runnerThread = 0;
                    foreach (BlockObject blockObject in putExtra.processes)
                    {
                        runnerThread加加;
                        while (runnerThread > (BaseBlockUtil.THREAD_NUN 加 1))
                        {
                            completionService.take().get();
                            runnerThread--;
                        }
                        if (dealEndDate < DateTime.Now)
                        {
                            dealEndDate = DateUtil.nextNMinutes(5, DateTime.Now);
                            putPolicy.deadline = Convert.ToString(DateUtil.ToJavaMilliseconds(DateUtil.nextNHours(1, DateTime.Now)));
                            token = TokenUtil.getUploadToken(putPolicy);
                        }
                        //RandomAccessFile blockFile = new RandomAccessFile(randomFile, "r");
                        blockObject.setCommonParam(randomFile, bucketName, fileKey);
                        HttpClient httpClient = new HttpClient();
                        BlockUpload task = new BlockUpload(blockObject, jsonObjectRet, putExtra, token, httpClient, uploadBatch);
                        completionService.submit(task);
                    }

                    for (int i = 0; i < runnerThread; i加加)
                    {
                        completionService.take().get();
                    }
                    pool.shutdown();

                    putPolicy.deadline = Convert.ToString(DateUtil.ToJavaMilliseconds(DateUtil.nextNHours(1, DateTime.Now)));
                    token = TokenUtil.getUploadToken(putPolicy);
                    mkfileHttpClient = WebRequestMethods.Http.HttpClient;
                    BaseBlockUtil util = new BaseBlockUtil(null, jsonObjectRet, putExtra, token, mkfileHttpClient);
                    SliceUploadHttpResult result = util.mkfile(token, fileKey, putExtra, 0, uploadBatch);


                    if (result.Status == 200)
                    {
                        string hash = WetagUtil.getEtagHash(randomFile);
                        if (result.Hash.Equals(hash))
                        {
                            jsonObjectRet.onSuccess(result.toJSON());
                            break;
                        }
                        else
                        {
                            Console.WriteLine(fileKey 加 " 文件hash与服务器不一致,文件重新上传");
                            putPolicy.overwrite = 1;
                            putExtra.processes = null;
                        }

                    }
                    else
                    {
                        if (result.Status == 412)
                        {
                            Console.WriteLine(fileKey 加 " 此文件块有缺失,文件重新上传");
                            putPolicy.overwrite = 1;
                            putExtra.processes = null;
                        }
                        else
                        {
                            jsonObjectRet.onFailure(new HttpClientException(result.Status, result.Response));
                            break;
                        }

                    }
                }
                catch (Exception e)
                {
                    jsonObjectRet.onFailure(e);
                }
                finally
                {
                    if (pool != null)
                    {
                        pool.shutdownNow();
                    }
                    if (mkfileHttpClient != null)
                    {
                        try
                        {
                            mkfileHttpClient.close();
                        }
                        catch (IOException)
                        {
                        }
                    }
                    if (randomFileInfo != null)
                    {
                        try
                        {
                            int reTime = 0;
                            while (!pool.Terminated && reTime < 50)
                            {
                                reTime加加;
                                Thread.Sleep(1000);
                            }
                        }
                        catch (Exception)
                        {
                            Console.WriteLine("file close error");
                        }
                    }
                }
            }
        }

C#ThreadPoolIt is relatively simple to use, you can refer to the document, mainly throughQueueUserWorkItem(WaitCallback)Method to start a task (thread task), where WaitCallback is a delegate that can be written using Lambda expressions.

In addition, you can also use System.Threading.Tasks.Task to implement the operation of the thread pool. the relevant information can be easily found on the internet.

In general, the thread pool of. NET does not need to deal with too many things of the thread pool itself, only needs to pay attention to the business. Regarding the size of the thread pool, you can use theThreadPool.SetMaxThreadsAndThreadPool.SetMinThreadsTo set, but generally do not need to deal with.