1
0
mirror of https://github.com/ppy/osu.git synced 2024-09-22 18:07:24 +08:00
osu-lazer/osu.Game/Database/DatabaseContextFactory.cs

95 lines
3.1 KiB
C#
Raw Normal View History

2018-01-05 19:21:19 +08:00
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
2017-10-17 15:02:13 +08:00
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
2018-02-12 16:55:11 +08:00
using System.Threading;
using osu.Framework.Platform;
namespace osu.Game.Database
{
public class DatabaseContextFactory : IDatabaseContextFactory
{
private readonly GameHost host;
private const string database_name = @"client";
2018-02-12 16:55:11 +08:00
private ThreadLocal<OsuDbContext> threadContexts;
private readonly object writeLock = new object();
private bool currentWriteDidWrite;
2018-02-12 16:55:11 +08:00
private volatile int currentWriteUsages;
public DatabaseContextFactory(GameHost host)
{
this.host = host;
2018-02-12 16:55:11 +08:00
recycleThreadContexts();
}
/// <summary>
/// Get a context for the current thread for read-only usage.
/// If a <see cref="DatabaseWriteUsage"/> is in progress, the existing write-safe context will be returned.
2018-02-12 16:55:11 +08:00
/// </summary>
public OsuDbContext Get() => threadContexts.Value;
/// <summary>
/// Request a context for write usage. Can be consumed in a nested fashion (and will return the same underlying context).
/// This method may block if a write is already active on a different thread.
/// </summary>
/// <returns>A usage containing a usable context.</returns>
public DatabaseWriteUsage GetForWrite()
{
Monitor.Enter(writeLock);
Interlocked.Increment(ref currentWriteUsages);
2018-02-13 13:58:15 +08:00
return new DatabaseWriteUsage(threadContexts.Value, usageCompleted);
}
2018-02-12 16:55:11 +08:00
private void usageCompleted(DatabaseWriteUsage usage)
{
int usages = Interlocked.Decrement(ref currentWriteUsages);
try
2018-02-12 16:55:11 +08:00
{
currentWriteDidWrite |= usage.PerformedWrite;
if (usages > 0) return;
if (currentWriteDidWrite)
{
2018-02-13 14:08:45 +08:00
// explicitly dispose to ensure any outstanding flushes happen as soon as possible (and underlying resources are purged).
usage.Context.Dispose();
currentWriteDidWrite = false;
2018-02-13 14:08:45 +08:00
// once all writes are complete, we want to refresh thread-specific contexts to make sure they don't have stale local caches.
recycleThreadContexts();
}
}
finally
{
Monitor.Exit(writeLock);
2018-02-12 16:55:11 +08:00
}
}
2018-02-13 14:08:45 +08:00
private void recycleThreadContexts() => threadContexts = new ThreadLocal<OsuDbContext>(CreateContext);
2018-02-12 16:55:11 +08:00
protected virtual OsuDbContext CreateContext()
{
var ctx = new OsuDbContext(host.Storage.GetDatabaseConnectionString(database_name));
ctx.Database.AutoTransactionsEnabled = false;
return ctx;
}
public void ResetDatabase()
{
2018-02-12 16:55:11 +08:00
lock (writeLock)
{
recycleThreadContexts();
host.Storage.DeleteDatabase(database_name);
}
}
}
}