Skip to content

Instantly share code, notes, and snippets.

@rolfbjarne
Created January 6, 2015 10:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rolfbjarne/9637a5a3892c5326314c to your computer and use it in GitHub Desktop.
Save rolfbjarne/9637a5a3892c5326314c to your computer and use it in GitHub Desktop.
class Test
{
public static void FontTest ()
{
var r=new Random();
for(int i=0; i<10; i++) {
new
System.Threading.Thread((System.Threading.ThreadStart)delegate {
while(true) {
Thread.Sleep(r.Next()&63);
using(var fw=FontTable.Add (UIFont.FromName("Helvetica", 20.0f))) {
var f = fw.Font;
Thread.Sleep(100);
Console.WriteLine(f.Ascender);
}
}
}).Start();
}
}
}
// This class is thread-safe.
// Call 'Add' to add an UIFont object to the table, and dispose the value
// returned from 'Add' when done with it.
public class FontTable
{
static Dictionary<IntPtr, int> dic = new Dictionary<IntPtr, int> ();
public static FontWrapper Add (UIFont obj)
{
lock (dic) {
int count;
if (dic.TryGetValue (obj.Handle, out count)) {
count++;
} else {
count = 1;
}
dic [obj.Handle] = count;
}
return new FontWrapper (obj);
}
internal static void Remove (UIFont obj)
{
lock (dic) {
int count;
if (!dic.TryGetValue (obj.Handle, out count))
throw new InvalidOperationException ("Remove called without a corresponding Add");
count--;
if (count == 0) {
dic.Remove (obj.Handle);
obj.Dispose ();
} else {
dic [obj.Handle] = count;
}
}
}
}
public class FontWrapper : IDisposable {
UIFont font;
public UIFont Font { get { return font; } }
public FontWrapper (UIFont font)
{
this.font = font;
}
public void Dispose ()
{
FontTable.Remove (font);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment