If there is a potential for multiple threads to do an insert / update into a SQLite database, should I always use lock?

末鹿安然 提交于 2020-01-11 11:58:31

问题


I have this code that uses lock:

            lock (l)
            {
                db2.BeginTransaction();
                try
                {
                    rc1 = db2.Execute(s);
                    db2.Commit();
                }
                catch (Exception ex)
                {
                    db2.Rollback();
                    Crashes.TrackError(ex,
                        new Dictionary<string, string> {
                            {"RunExecute", "Exception"},
                            {"sql", s },
                            {"Device Model", DeviceInfo.Model },
                        });
                    throw;
                }
            }

and other code that doesn't:

            db2.Insert(new QuizHistory()
            {
                QuizId = quiz,
                Cards  = (App.viewablePhrases ?? GetViewablePhrases(MO.Quiz)).Count,
                Score = score,
                UtcNow = (int)Math.Truncate(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds),
                Viewed = 1,
                Deck   = Helpers.Deck.GetTitle()
            });

To reduce the chance of issues, should I be adding lock(l) around all the code that accesses the database?

来源:https://stackoverflow.com/questions/59092880/if-there-is-a-potential-for-multiple-threads-to-do-an-insert-update-into-a-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!