异步插入用户操作到数据库,而不是产生大量的线程C#

时间:2015-06-29 10:45:56

标签: c# multithreading blockingcollection

我正在尝试构建这个分析系统,这会将数据推送到用户执行的特定操作的数据库。

将会有多个需要记录的操作,因此需要异常完成,但它不会产生许多线程,需要将其置于低优先级而不会妨碍系统的性能,我在想使用阻塞集合,即继续推送集合中的数据并选择它们以保存到数据库中。

我还没有真正实现这个目标,有人能给我一个如何实现这个目标的例子吗?

1 个答案:

答案 0 :(得分:1)

嗨,你的问题既不具体也不公正(因此投票)。

尽管如此,这里有一些代码行可以帮助您入门:

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

namespace ParallelTest
{
    static class Program
    {
        static readonly Stopwatch Stopwatch = new Stopwatch();

        static void Main()
        {
            Stopwatch.Start();
            var myList = new List<string>();
            for (var i = 0; i < 10000; i++)
                myList.Add(string.Format("String Item or Object Nr. {0:00000000}", i));

            Debug.WriteLine("End Create In-Memory List: {0}", Stopwatch.Elapsed);

            // NON-PARELLEL
            Stopwatch.Restart();
            myList.ForEach(item =>
            {
                // ... Do something
                Thread.Sleep(1);
            });

            Debug.WriteLine("NON-PARALLEL LIST: {0}", Stopwatch.Elapsed);
            // ------------------------------------------------------------------------


            // If you don't need to edit the collection at runtime you can use a normal 
            // list with Parallel options

            // PARALLEL (MULTITHREADED)
            // Example with unlimited Thread (CLR auto-manages, be careful 
            // with SQL-Connections)
            Stopwatch.Restart();
            Parallel.ForEach(myList, item =>
            {
                // ... Do something
                Thread.Sleep(1);
            });
            Debug.WriteLine("PARALLEL LIST: {0}", Stopwatch.Elapsed);
            // ------------------------------------------------------------------------


            // If you don't need to edit the collection at runtime you can use a normal 
            // list with Parallel options

            // PARALLEL WITH LIMITED THREADS
            // Example with 2 Threads
            Stopwatch.Restart();
            Parallel.ForEach(myList, 
                new ParallelOptions { MaxDegreeOfParallelism = 2 }, item =>
            {
                // ... Do something
                Thread.Sleep(1);
            });
            Debug.WriteLine("PARALLEL LIST 2 THREADS: {0}", Stopwatch.Elapsed);
            // ------------------------------------------------------------------------

            // If you need to make changes to the list during runtime you need to use 
            // a thread-safe collection type such as BlockingCollection
            // Avoid race-conditions

            // See examples under 
            // https://msdn.microsoft.com/en-us/library/dd997306(v=vs.110).aspx
        }
    }
}

System.Parallel on MSDN