/// <summary> /// 为辅助线程提供,在主线程中执行逻辑 /// </summary> /// <param name="action">委托</param> /// <param name="delay">延迟时间</param> public void ExecuteOnMainThread(Action action, float delay = 0) { var item = new DelayedItem() { Action = action, Time = DateTime.Now.AddSeconds(delay) }; delayedItemActionList.Add(item); }
/// <summary> /// 执行需要在主线程调用的方法 由辅助线程调用 /// </summary> /// <param name="action">需要执行的方法</param> /// <param name="time">延迟时间</param> public void ExecuteOnMainThread(Action action, float time = 0) { lock (delayedActionList) { var item = new DelayedItem() { CurrentAction = action, Time = DateTime.Now.AddSeconds(time) }; delayedActionList.Add(item); } }
/// <summary> /// 在主线程执行方法 /// </summary> /// <param name="handle"></param> /// <param name="delay"></param> public void ExecuteOnMainThread(Action handle, float delay = 0) { //添加元素 与 删除元素 排队执行。 lock (list) { var item = new DelayedItem() { CurrentAction = handle, Time = DateTime.Now.AddSeconds(delay) }; list.Add(item); } }
public void Should_able_unblock_when_item_matched_to_condition_after_some_delay() { using (var queue = new BlockingQueue <DelayedItem>(5)) { var expectedResults = Enumerable.Range(1, 10).ToArray(); int[] allItems = null; var producer = Task.Run( () => { for (var i = 0; i < 10; i++) { var item = new DelayedItem("delay value", i + 1, i % 2 == 0 ? 5 : 0); queue.Enqueue(item); output.WriteLine($"Enqueue {item.ResultAfterDelay}"); } }); var consumer = Task.Run( () => { var items = new List <int>(); while (items.Count < 10) { if (queue.TryDequeIfHeadMatched(x => x.Result is int, out var item)) { output.WriteLine($"Consumer checks result {item.ResultChecksCount} times"); items.Add((int)item.Result); } } allItems = items.ToArray(); }); var task = Task.WhenAll(producer, consumer); task.Wait(LongWait); task.IsCompleted.Should().BeTrue(); PrintAllItems(allItems); allItems.Should().HaveSameCount(expectedResults); allItems.Should().BeEquivalentTo(expectedResults); } }