2 * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
4 * Licensed under the Apache License, Version 2.0 (the License);
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an AS IS BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 using System.Collections.Concurrent;
19 using System.Threading;
21 namespace Tizen.Applications
25 /// Provides a synchronization context for the Tizen application model.
27 public class TizenSynchronizationContext : SynchronizationContext
29 private readonly Interop.Glib.GSourceFunc _wrapperHandler;
30 private readonly Object _transactionLock = new Object();
31 private readonly ConcurrentDictionary<int, Action> _handlerMap = new ConcurrentDictionary<int, Action>();
32 private int _transactionId = 0;
35 /// Initializes a new instance of the TizenSynchronizationContext class.
37 public TizenSynchronizationContext()
39 _wrapperHandler = new Interop.Glib.GSourceFunc(Handler);
43 /// Initilizes a new TizenSynchronizationContext and install into current thread
48 /// SetSynchronizationContext(new TizenSynchronizationContext());
51 public static void Initialize()
53 SetSynchronizationContext(new TizenSynchronizationContext());
58 /// Dispatches an asynchronous message to a Tizen main loop.
60 /// <param name="d"><see cref="System.Threading.SendOrPostCallback"/>The SendOrPostCallback delegate to call.</param>
61 /// <param name="state"><see cref="System.Object"/>The object passed to the delegate.</param>
63 /// The Post method starts an asynchronous request to post a message.</remarks>
64 public override void Post(SendOrPostCallback d, object state)
73 /// Dispatches a synchronous message to a Tizen main loop
75 /// <param name="d"><see cref="System.Threading.SendOrPostCallback"/>The SendOrPostCallback delegate to call.</param>
76 /// <param name="state"><see cref="System.Object"/>The object passed to the delegate.</param>
78 /// The Send method starts a synchronous request to send a message.</remarks>
79 public override void Send(SendOrPostCallback d, object state)
81 var mre = new ManualResetEvent(false);
105 private void Post(Action action)
108 lock (_transactionLock)
110 id = _transactionId++;
112 _handlerMap.TryAdd(id, action);
113 Interop.Glib.IdleAdd(_wrapperHandler, (IntPtr)id);
116 private bool Handler(IntPtr userData)
118 int key = (int)userData;
119 if (_handlerMap.ContainsKey(key))
122 _handlerMap.TryRemove(key, out action);