aboutsummaryrefslogtreecommitdiffstats
path: root/Tests/Test_QtVsTools.Core/Test_LazyFactory.cs
blob: d05b62d1d47fe2b2cf2612f100af6031a65cf80c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// Copyright (C) 2025 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

using System.Collections.Concurrent;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace QtVsTools.Test.Core
{
    using Common;

    [TestClass]
    public class Test_LazyFactory
    {
        class LazyClass
        {
            LazyFactory Lazy { get; } = new();
            public ConcurrentBag<int> InitThread { get; } = new();
            public string LazyProperty => Lazy.Get(() =>
                LazyProperty, () =>
                {
                    InitThread.Add(Thread.CurrentThread.ManagedThreadId);
                    return "LAZYVALUE";
                });
        }

        [TestMethod]
        public void Test_ThreadSafety()
        {
            var lazyObject = new LazyClass();
            var task = Task.Run(async () =>
            {
                var tasks = new Task[3000];
                for (int i = 0; i < tasks.Length; i++) {
                    var n = i;
                    tasks[i] = Task.Run(() =>
                    {
                        var lazyValue = lazyObject.LazyProperty;
                        Debug.WriteLine($"Lazy value #{n} is {lazyValue}");
                    });
                }
                await Task.WhenAll(tasks);
            });
            while (!task.IsCompleted)
                Thread.Sleep(100);

            Assert.IsTrue(lazyObject.InitThread.Count ==  1);
        }
    }
}