欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#程序執(zhí)行時(shí)間長查詢速度慢解決方案

 更新時(shí)間:2020年07月13日 09:57:57   作者:葉丶梓軒  
這篇文章主要介紹了C#程序執(zhí)行時(shí)間長查詢速度慢解決方案,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

一,程序執(zhí)行慢導(dǎo)致的原因就是查詢數(shù)據(jù)庫慢.,導(dǎo)致返回值慢,那這個(gè)要怎么解決呢?

1,優(yōu)化數(shù)據(jù)庫查詢?nèi)邕@個(gè)文章 C#導(dǎo)出數(shù)據(jù)到excel如何提升性能

2,使用線程并行查詢,然后合并成一個(gè)集合,代碼如下,必須留意備注的核心點(diǎn)

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace TestConsoleApp
{
  /// <summary>
  ///C#慢查詢解決: 線程并行實(shí)現(xiàn)處理
  /// </summary>
  class Program
  {
    static void Main(string[] args)
    {
      List<Task> taskList = new List<Task>();
      int count = 100;
      int batch = count % 10;
      object lockObj = new object();
      List<int> list = new List<int>();

      ///開啟線程并行執(zhí)行
      Stopwatch stopwatch = new Stopwatch();
      stopwatch.Start();
      for (int i = 0; i < batch; i++)
      {
        taskList.Add(Task.Run(() =>
        {
          for (int j = count * i; j < count * (i + 1); j++)
          {
            ///休眠等待,模擬慢查詢需要消耗的時(shí)間
            Thread.Sleep(100);
            ///核心邏輯:避免線程插入沖突
            lock (lockObj)
            {
              list.Add(i);
            }
          }
        }));
      }
      ///這里核心是等待所有的線程結(jié)束,然后再執(zhí)行下去
      Task.WaitAll(taskList.ToArray());
      ///這里再內(nèi)存處理排序,避免返回的結(jié)果跟正常查詢出來的結(jié)果排序不一致
      list = list.OrderByDescending(u => u).ToList();
      Console.WriteLine(stopwatch.ElapsedMilliseconds);


      Console.WriteLine("**********分割線***********");

      ///原始遍歷實(shí)現(xiàn)
      List<int> list2 = new List<int>();
      Stopwatch stopwatch2 = new Stopwatch();
      stopwatch2.Start();
      for (int i = 0; i < count; i++)
      {
        ///休眠等待,模擬慢查詢需要消耗的時(shí)間
        Thread.Sleep(100);
        list2.Add(i);
      }
      Console.WriteLine(stopwatch2.ElapsedMilliseconds);
      Console.ReadLine();
    }
  }
}

PS:核心點(diǎn)

1》線程等待線程結(jié)束Task.WaitAll

2》鎖住集合,以防插入占用導(dǎo)致報(bào)錯

3》結(jié)果需要排序,因?yàn)椴⑿芯€程的結(jié)果是亂序的

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論