|
| 1 | +using System; |
| 2 | +using System.Diagnostics; |
| 3 | +using System.Threading; |
| 4 | + |
| 5 | +using Foundation; |
| 6 | +using ObjCRuntime; |
| 7 | + |
| 8 | +using Bindings.Test; |
| 9 | + |
| 10 | +using NUnit.Framework; |
| 11 | + |
| 12 | +using Xamarin.Utils; |
| 13 | + |
| 14 | +namespace MonoTouchFixtures.ObjCRuntime { |
| 15 | + [TestFixture] |
| 16 | + [Preserve (AllMembers = true)] |
| 17 | + public class NativeWeakTest { |
| 18 | + [Test] |
| 19 | + public void TestWeakReferences () |
| 20 | + { |
| 21 | + var start = Stopwatch.StartNew (); |
| 22 | + |
| 23 | + var gcThread = new Thread (() => { |
| 24 | + while (start.Elapsed.TotalSeconds < 5) { |
| 25 | + GC.Collect (); |
| 26 | + Thread.Sleep (100); |
| 27 | + } |
| 28 | + }) { |
| 29 | + IsBackground = true, |
| 30 | + }; |
| 31 | + gcThread.Start (); |
| 32 | + |
| 33 | + int nilObjectCount = 0; |
| 34 | + int nonNilObjectCount = 0; |
| 35 | + int gotExpectedResponse = 0; |
| 36 | + int gotUnexpectedResponse = 0; |
| 37 | + int gotFinalizedResponse = 0; |
| 38 | + |
| 39 | + const int objectCount = 100; |
| 40 | + |
| 41 | + var creatorThread = new Thread (() => { |
| 42 | + using var holder = new WeakReferenceHolder (); |
| 43 | + for (var i = 0; i < objectCount; i++) { |
| 44 | + holder.AddObject (new MyWeakReferencedObject ()); |
| 45 | + } |
| 46 | + GC.Collect (); |
| 47 | + GC.WaitForPendingFinalizers (); |
| 48 | + |
| 49 | + holder.CallDoSomething (ref nilObjectCount, ref nonNilObjectCount, ref gotExpectedResponse, ref gotUnexpectedResponse, ref gotFinalizedResponse); |
| 50 | + }) { |
| 51 | + IsBackground = true, |
| 52 | + }; |
| 53 | + creatorThread.Start (); |
| 54 | + |
| 55 | + Assert.That (creatorThread.Join (TimeSpan.FromSeconds (15)), "Join CreatorThread"); |
| 56 | + |
| 57 | + var msg = $"Nil object count: {nilObjectCount} Non-nil object count: {nonNilObjectCount} Expected response: {gotExpectedResponse} Unexpected responses: {gotUnexpectedResponse} Finalized response: {gotFinalizedResponse}"; |
| 58 | + Assert.Multiple (() => { |
| 59 | + Assert.That (nonNilObjectCount, Is.EqualTo (objectCount - nilObjectCount), $"Non-nil object count: {msg}"); |
| 60 | + Assert.That (gotExpectedResponse, Is.EqualTo (objectCount - nilObjectCount), $"Expected response count: {msg}"); |
| 61 | + Assert.That (gotUnexpectedResponse, Is.EqualTo (0), $"Unexpected response count: {msg}"); |
| 62 | + Assert.That (gotFinalizedResponse, Is.EqualTo (0), $"Responses after finalization: {msg}"); |
| 63 | + }); |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + class MyWeakReferencedObject : WeakReferencedObject { |
| 68 | + bool finalized; |
| 69 | + |
| 70 | + public override int DoSomething () |
| 71 | + { |
| 72 | + return finalized ? 314 : 42; |
| 73 | + } |
| 74 | + |
| 75 | + ~MyWeakReferencedObject () |
| 76 | + { |
| 77 | + finalized = true; |
| 78 | + } |
| 79 | + } |
| 80 | +} |
0 commit comments