实体框架串行事务需要太多时间才能完成

发布于 2024-12-28 13:20:30 字数 2730 浏览 0 评论 0原文

我正在编写一个串行事务,遇到了一些麻烦。
如果我只执行一个线程,它执行速度很快,无需等待。
如果我执行两个或多个线程,第一个完成的线程需要太多时间,但后续线程很快,为什么?

如果我同时运行该程序的两个进程,每个进程的第一个线程需要太多时间才能完成,但后续线程很快,这正常吗?

我正在使用 sql express 2008

谢谢。

class Program {

    int numero;

    Program(int numero)
    {
        this.numero = numero;
    }

    static void Main(string[] args)
    {
        Console.WriteLine("Puede presionar una tecla para salir en cualquier momento");

        for (int i = 0; i < 10; i++)
        {
            Program p = new Program(i + 1);
            Thread t = new Thread(p.Ejecutar);
            t.Start();
        }

        Console.ReadKey();
    }

    public void Ejecutar()
    {  
        bool esPosibleProseguir = true;
        while (esPosibleProseguir)
        {
            Database1Entities cx = new Database1Entities();
            TransactionOptions opts = new TransactionOptions();
            opts.IsolationLevel = System.Transactions.IsolationLevel.Serializable;
            System.Transactions.TransactionScope scope = new System.Transactions.TransactionScope(TransactionScopeOption.Required, opts);

            try
            {
                //var mayor = cx.Numeracion.First();
                //int nuevo = mayor.Numero + 1;
                cx.Connection.Open();

                int nuevo = cx.VistaNumero.First().Actual;

                var per = new Persona();
                per.Nombre = string.Format("Persona-{0}", nuevo);
                per.Ci = (1000 + nuevo).ToString();
                per.Numero = nuevo;
                cx.Persona.AddObject(per);

                //mayor.Numero = nuevo;

                cx.SaveChanges();
                scope.Complete();


                Console.WriteLine("Hilo: {0}, Crea persona: {1}", this.numero, nuevo);
                break;
            }
            catch (UpdateException ex1)
            {
                esPosibleProseguir = true;
            }
            catch (TransactionAbortedException ex2)
            {
                esPosibleProseguir = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Hilo: {0}, Excepción: {1}, Mensaje: {2}", this.numero, ex.GetType().Name, ex.Message);
                esPosibleProseguir = false;
            }
            finally
            {
                DisponerObjeto(scope);
                DisponerObjeto(cx);
            }
        }
    }

    private void DisponerObjeto(IDisposable obj)
    {
        try
        {
            obj.Dispose();
        }
        catch (Exception ex)
        {
            Console.WriteLine("Hilo: {0}, Excepción: {1}, Mensaje: {2}", this.numero, ex.GetType().Name, ex.Message);
        }
    }
}

I am writing a serial transaction and had some troubles.
If I only execute one thread, it executes fast, no waiting.
If I execute two or more threads, the first thread that complete takes too much time but subsequent threads are fast, why?

If I run two process concurrently of this program, each process's first thread takes too much time to complete but subsequent are fast, is this normal?

I am using sql express 2008

thanks.

class Program {

    int numero;

    Program(int numero)
    {
        this.numero = numero;
    }

    static void Main(string[] args)
    {
        Console.WriteLine("Puede presionar una tecla para salir en cualquier momento");

        for (int i = 0; i < 10; i++)
        {
            Program p = new Program(i + 1);
            Thread t = new Thread(p.Ejecutar);
            t.Start();
        }

        Console.ReadKey();
    }

    public void Ejecutar()
    {  
        bool esPosibleProseguir = true;
        while (esPosibleProseguir)
        {
            Database1Entities cx = new Database1Entities();
            TransactionOptions opts = new TransactionOptions();
            opts.IsolationLevel = System.Transactions.IsolationLevel.Serializable;
            System.Transactions.TransactionScope scope = new System.Transactions.TransactionScope(TransactionScopeOption.Required, opts);

            try
            {
                //var mayor = cx.Numeracion.First();
                //int nuevo = mayor.Numero + 1;
                cx.Connection.Open();

                int nuevo = cx.VistaNumero.First().Actual;

                var per = new Persona();
                per.Nombre = string.Format("Persona-{0}", nuevo);
                per.Ci = (1000 + nuevo).ToString();
                per.Numero = nuevo;
                cx.Persona.AddObject(per);

                //mayor.Numero = nuevo;

                cx.SaveChanges();
                scope.Complete();


                Console.WriteLine("Hilo: {0}, Crea persona: {1}", this.numero, nuevo);
                break;
            }
            catch (UpdateException ex1)
            {
                esPosibleProseguir = true;
            }
            catch (TransactionAbortedException ex2)
            {
                esPosibleProseguir = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Hilo: {0}, Excepción: {1}, Mensaje: {2}", this.numero, ex.GetType().Name, ex.Message);
                esPosibleProseguir = false;
            }
            finally
            {
                DisponerObjeto(scope);
                DisponerObjeto(cx);
            }
        }
    }

    private void DisponerObjeto(IDisposable obj)
    {
        try
        {
            obj.Dispose();
        }
        catch (Exception ex)
        {
            Console.WriteLine("Hilo: {0}, Excepción: {1}, Mensaje: {2}", this.numero, ex.GetType().Name, ex.Message);
        }
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

晨敛清荷 2025-01-04 13:20:30

这可能是因为第一次执行 EF 相关代码会导致“模型编译”加上一些其他初始化,这是相当耗时的操作,并且在该编译完成之前没有其他人可以使用 EF。这只是一个猜测,但您可以尝试使用预编译模型来验证如果执行时间会改善。

It can be because first execution of EF related code causes "model compilation" plus some other initializations which is quite time consuming operation and until this compilation is done no one else can use EF. It is just a guess but you can try to use percompiled model to validate if execution time would improve.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文