public static void AsyncExecutor(Action action, AsyncOptions options)
 {
     if (options.ExecuteCallbackOnMainThread)
     {
         if (UnityInitializer.IsMainThread())
         {
             SafeExecute(action);
         }
         else
         {
             UnityRequestQueue.Instance.ExecuteOnMainThread(action);
         }
     }
     else
     {
         if (!UnityInitializer.IsMainThread())
         {
             SafeExecute(action);
         }
         else
         {
             ThreadPool.QueueUserWorkItem((state) =>
             {
                 SafeExecute(action);
             });
         }
     }
 }
Beispiel #2
0
        /// <summary>
        /// Returns the HTTP response.
        /// </summary>
        /// <returns>The HTTP response.</returns>
        public IWebResponseData GetResponse()
        {
            if (UnityInitializer.IsMainThread())
            {
                throw new Exception("Network on game thread");
            }

            this.IsSync     = true;
            this.WaitHandle = new ManualResetEvent(false);
            try
            {
                UnityRequestQueue.Instance.EnqueueRequest(this);
                this.WaitHandle.WaitOne();

                if (this.Exception != null)
                {
                    throw this.Exception;
                }

                return(this.Response);
            }
            finally
            {
                this.WaitHandle.Close();
            }
        }
        /// <summary>
        /// Returns the HTTP response.
        /// </summary>
        /// <returns>The HTTP response.</returns>
        public IWebResponseData GetResponse()
        {
            if (UnityInitializer.IsMainThread())
            {
                throw new Exception("Cannot execute synchronous calls on game thread");
            }

            this.IsSync     = true;
            this.WaitHandle = new ManualResetEvent(false);
            try
            {
                UnityRequestQueue.Instance.EnqueueRequest(this);
                this.WaitHandle.WaitOne();

                if (this.Exception != null)
                {
                    throw this.Exception;
                }

                //timeout scenario
                if (this.Exception == null && this.Response == null)
                {
                    throw new WebException("Request timed out", WebExceptionStatus.Timeout);
                }

                return(this.Response);
            }
            finally
            {
                this.WaitHandle.Close();
            }
        }
 public override IAsyncResult InvokeAsync(IAsyncExecutionContext executionContext)
 {
     if (UnityInitializer.IsMainThread())
     {
         _throttler.Enqueue(executionContext, InvokeAsyncHelper, ErrorCallback);
         return(null);
     }
     return(base.InvokeAsync(executionContext));
 }
Beispiel #5
0
        private void SaveSessionStorage()
        {
            _sessionStorage._startTime    = StartTime;
            _sessionStorage._stopTime     = StopTime;
            _sessionStorage._preStartTime = PreStartTime;
            _sessionStorage._sessionId    = SessionId;
            _sessionStorage._duration     = Duration;

            // store session into file
            _logger.DebugFormat("Mobile Analytics is about to store session info: {0} ", JsonMapper.ToJson(_sessionStorage));
#if PCL
            IFolder rootFolder = FileSystem.Current.LocalStorage;
            IFile   file       = rootFolder.CreateFileAsync(_sessionStorageFileFullPath, CreationCollisionOption.ReplaceExisting).Result;
            file.WriteAllTextAsync(JsonMapper.ToJson(_sessionStorage)).Wait();
#elif BCL
            string directory = Path.GetDirectoryName(_sessionStorageFileFullPath);
            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }
            File.WriteAllText(_sessionStorageFileFullPath, JsonMapper.ToJson(_sessionStorage));
#elif UNITY
            Action action = () =>
            {
                // create a file to store session info
                if (!File.Exists(_sessionStorageFileFullPath))
                {
                    FileStream fs = File.Create(_sessionStorageFileFullPath);
                    fs.Close();

                    File.WriteAllText(_sessionStorageFileFullPath, JsonMapper.ToJson(_sessionStorage));
                }
                else
                {
                    File.WriteAllText(_sessionStorageFileFullPath, String.Empty);
                    File.WriteAllText(_sessionStorageFileFullPath, JsonMapper.ToJson(_sessionStorage));
                }
            };


            if (UnityInitializer.IsMainThread())
            {
                action();
            }
            else
            {
                ManualResetEvent e = new ManualResetEvent(false);
                UnityRequestQueue.Instance.ExecuteOnMainThread(() =>
                {
                    action();
                    e.Set();
                });
                e.WaitOne();
            }
#endif
        }
Beispiel #6
0
 private void EnsureBackgroundExecution(Action action)
 {
     if (UnityInitializer.IsMainThread())
     {
         ThreadPool.QueueUserWorkItem(new WaitCallback(delegate
         {
             action.Invoke();
         }));
     }
     else
     {
         action.Invoke();
     }
 }
Beispiel #7
0
 public override void Clear(string key)
 {
     if (UnityInitializer.IsMainThread())
     {
         ClearHelper(key);
     }
     else
     {
         UnityRequestQueue.Instance.ExecuteOnMainThread(() =>
         {
             ClearHelper(key);
         });
     }
 }
 public override void Put(string key, string value)
 {
     if (UnityInitializer.IsMainThread())
     {
         PutHelper(key, value);
     }
     else
     {
         UnityRequestQueue.Instance.ExecuteOnMainThread(() =>
         {
             PutHelper(key, value);
         });
     }
 }
Beispiel #9
0
        private void SaveSessionStorage()
        {
            lock (_lock)
            {
                _sessionStorage._startTime        = _startTime;
                _sessionStorage._stopTime         = _stopTime;
                _sessionStorage._preStartTime     = _preStartTime;
                _sessionStorage._sessionId        = _sessionId;
                _sessionStorage._duration         = _duration;
                _sessionStorage._globalAttributes = CustomEvent.GetGlobalAttributes();
                _sessionStorage._globalMetrics    = CustomEvent.GetGlobalMetrics();
            }

            // store session into file
            _logger.DebugFormat("Mobile Analytics is about to store session info: {0} ", JsonMapper.ToJson(_sessionStorage));

            Action action = () =>
            {
                // create a file to store session info
                if (!File.Exists(_sessionStorageFilePath))
                {
                    FileStream fs = File.Create(_sessionStorageFilePath);
                    fs.Close();

                    File.WriteAllText(_sessionStorageFilePath, JsonMapper.ToJson(_sessionStorage));
                }
                else
                {
                    File.WriteAllText(_sessionStorageFilePath, String.Empty);
                    File.WriteAllText(_sessionStorageFilePath, JsonMapper.ToJson(_sessionStorage));
                }
            };


            if (UnityInitializer.IsMainThread())
            {
                action();
            }
            else
            {
                ManualResetEvent e = new ManualResetEvent(false);
                UnityRequestQueue.Instance.ExecuteOnMainThread(() =>
                {
                    action();
                    e.Set();
                });
                e.WaitOne();
            }
        }
Beispiel #10
0
 public override void Put(string key, string value)
 {
     if (UnityInitializer.IsMainThread())
     {
         PutHelper(key, value);
     }
     else
     {
         AutoResetEvent asyncEvent = new AutoResetEvent(false);
         UnityRequestQueue.Instance.ExecuteOnMainThread(() =>
         {
             PutHelper(key, value);
             asyncEvent.Set();
         });
         asyncEvent.WaitOne();
     }
 }
Beispiel #11
0
        public override string Get(string key)
        {
            if (UnityInitializer.IsMainThread())
            {
                return(GetHelper(key));
            }
            string         value      = string.Empty;
            AutoResetEvent asyncEvent = new AutoResetEvent(initialState: false);

            UnityRequestQueue.Instance.ExecuteOnMainThread(delegate
            {
                value = GetHelper(key);
                asyncEvent.Set();
            });
            asyncEvent.WaitOne();
            return(value);
        }
Beispiel #12
0
        private void RetrieveSessionStorage()
        {
            string sessionString = null;

            Action action = () =>
            {
                if (File.Exists(_sessionStorageFilePath))
                {
                    System.IO.StreamReader sessionFile = new System.IO.StreamReader(_sessionStorageFilePath);
                    sessionString = sessionFile.ReadToEnd();
                    sessionFile.Close();
                    _logger.DebugFormat("Mobile Analytics retrieves session info: {0}", sessionString);
                }
                else
                {
                    _logger.DebugFormat("Mobile Analytics session file does not exist.");
                }
            };


            if (UnityInitializer.IsMainThread())
            {
                action();
            }
            else
            {
                ManualResetEvent e = new ManualResetEvent(false);
                UnityRequestQueue.Instance.ExecuteOnMainThread(() =>
                {
                    action();
                    e.Set();
                });

                e.WaitOne();
            }


            if (!string.IsNullOrEmpty(sessionString))
            {
                _sessionStorage = JsonMapper.ToObject <SessionStorage>(sessionString);
            }
        }
Beispiel #13
0
        public static NetworkReachability GetReachability()
        {
            //if the thread is main thread. Then return the rechability status directly
            if (UnityInitializer.IsMainThread())
            {
                return(Application.internetReachability);
            }
            else
            {
                NetworkReachability _networkReachability = NetworkReachability.NotReachable;
                AutoResetEvent      asyncEvent           = new AutoResetEvent(false);
                UnityRequestQueue.Instance.ExecuteOnMainThread(() =>
                {
                    _networkReachability = Application.internetReachability;
                    asyncEvent.Set();
                });
                asyncEvent.WaitOne();

                return(_networkReachability);
            }
        }
Beispiel #14
0
        /// <summary>
        /// Synchronize <see cref="Dataset"/> between local storage and remote storage.
        /// </summary>
        public virtual void Synchronize()
        {
            if (NetworkInfo.GetReachability() == NetworkReachability.NotReachable)
            {
                FireSyncFailureEvent(new NetworkException("Network connectivity unavailable."));
                return;
            }

            // if the thread is in background thread, then start synchronizing,
            // else queue the synchronization in a threadpool thread
            if (!UnityInitializer.IsMainThread())
            {
                SynchronizeInternalAsync();
            }
            else
            {
                ThreadPool.QueueUserWorkItem(new WaitCallback(delegate
                {
                    SynchronizeInternalAsync();
                }));
            }
        }
Beispiel #15
0
        private void RetrieveSessionStorage()
        {
            string sessionString = null;

#if PCL
            IFolder rootFolder = FileSystem.Current.LocalStorage;
            if (ExistenceCheckResult.FileExists == rootFolder.CheckExistsAsync(_sessionStorageFileFullPath).Result)
            {
                IFile file = rootFolder.GetFileAsync(_sessionStorageFileFullPath).Result;
                sessionString = file.ReadAllTextAsync().Result;
            }
#elif BCL
            if (File.Exists(_sessionStorageFileFullPath))
            {
                using (var sessionFile = new System.IO.StreamReader(_sessionStorageFileFullPath))
                {
                    sessionString = sessionFile.ReadToEnd();
                    sessionFile.Close();
                }
                _logger.DebugFormat("Mobile Analytics retrieves session info: {0}", sessionString);
            }
            else
            {
                _logger.DebugFormat("Mobile Analytics session file does not exist.");
            }
#elif UNITY
            Action action = () =>
            {
                if (File.Exists(_sessionStorageFileFullPath))
                {
                    System.IO.StreamReader sessionFile = new System.IO.StreamReader(_sessionStorageFileFullPath);
                    sessionString = sessionFile.ReadToEnd();
                    sessionFile.Close();
                    _logger.DebugFormat("Mobile Analytics retrieves session info: {0}", sessionString);
                }
                else
                {
                    _logger.DebugFormat("Mobile Analytics session file does not exist.");
                }
            };


            if (UnityInitializer.IsMainThread())
            {
                action();
            }
            else
            {
                ManualResetEvent e = new ManualResetEvent(false);
                UnityRequestQueue.Instance.ExecuteOnMainThread(() =>
                {
                    action();
                    e.Set();
                });

                e.WaitOne();
            }
#endif
            if (!string.IsNullOrEmpty(sessionString))
            {
                _sessionStorage = JsonMapper.ToObject <SessionStorage>(sessionString);
            }
        }