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 /// <since_tizen> 3 </since_tizen>
28 public class TizenSynchronizationContext : SynchronizationContext
30 private readonly Interop.Glib.GSourceFunc _wrapperHandler;
31 private readonly Object _transactionLock = new Object();
32 private readonly ConcurrentDictionary<int, Action> _handlerMap = new ConcurrentDictionary<int, Action>();
33 private int _transactionId = 0;
36 /// Initializes a new instance of the TizenSynchronizationContext class.
38 /// <since_tizen> 3 </since_tizen>
39 public TizenSynchronizationContext()
41 _wrapperHandler = new Interop.Glib.GSourceFunc(Handler);
45 /// Initilizes a new TizenSynchronizationContext and install into the current thread.
50 /// SetSynchronizationContext(new TizenSynchronizationContext());
53 /// <since_tizen> 3 </since_tizen>
54 public static void Initialize()
56 SetSynchronizationContext(new TizenSynchronizationContext());
61 /// Dispatches an asynchronous message to a Tizen main loop.
63 /// <param name="d"><see cref="System.Threading.SendOrPostCallback"/>The SendOrPostCallback delegate to call.</param>
64 /// <param name="state"><see cref="System.Object"/>The object passed to the delegate.</param>
66 /// The post method starts an asynchronous request to post a message.</remarks>
67 /// <since_tizen> 3 </since_tizen>
68 public override void Post(SendOrPostCallback d, object state)
77 /// Dispatches a synchronous message to a Tizen main loop.
79 /// <param name="d"><see cref="System.Threading.SendOrPostCallback"/>The SendOrPostCallback delegate to call.</param>
80 /// <param name="state"><see cref="System.Object"/>The object passed to the delegate.</param>
82 /// The send method starts a synchronous request to send a message.</remarks>
83 /// <since_tizen> 3 </since_tizen>
84 public override void Send(SendOrPostCallback d, object state)
86 var mre = new ManualResetEvent(false);
110 private void Post(Action action)
113 lock (_transactionLock)
115 id = _transactionId++;
117 _handlerMap.TryAdd(id, action);
118 Interop.Glib.IdleAdd(_wrapperHandler, (IntPtr)id);
121 private bool Handler(IntPtr userData)
123 int key = (int)userData;
124 if (_handlerMap.ContainsKey(key))
127 _handlerMap.TryRemove(key, out action);