public virtual void Init(IndexReader reader) { this.reader = reader; timeElapsed = 0; t = new ThreadJob(new System.Threading.ThreadStart(this.Run)); t.Start(); }
/// <summary> /// 线程异步读取文件 /// </summary> /// <param name="relativeStreamingAssetPath"></param> /// <param name="compelted"></param> /// <returns></returns> public static Action ReadFileAsync(string relativeStreamingAssetPath, Action <byte[]> compelted) { var filePath = PathUtils.TryGetTargetFilePath(relativeStreamingAssetPath); ThreadJob <byte[]> task = new ThreadJob <byte[]>(() => { #if UNITY_EDITOR || UNITY_IPHONE var bytes = File.ReadAllBytes(filePath); bytes = XOR.Decrypt(bytes); return(bytes); #elif UNITY_ANDROID var bytes = BetterStreamingAssets.ReadAllBytes(streamingAssetPath); bytes = XOR.Decrypt(bytes); return(bytes); #else var bytes = File.ReadAllBytes(filePath); bytes = XOR.Decrypt(bytes); return(bytes); #endif }); Action doStart = () => { task.ContinueOnUIThread((r) => { compelted(r.Result); }); task.Start(); }; doStart(); return(() => { task.Abort(); }); }
private IEnumerator SaveAnalyticsData() { yield return(m_threadJob.WaitFor()); bool result = false; m_threadJob.Start(() => result = SaveAnalyticsDataToFile() ); yield return(m_threadJob.WaitFor()); }
public RTPRobotScanner() { _robotCommunicator = new RTPRobotCommunicator(); _dataCommunicator = new RTPDataCommunicator(); _dataCommunicator.Start(); _dataCommunicator.OnRobotInfoDetected += OnRobotInfoDetected; _thread = new ThreadJob(); _thread.ThreadHandler += ThreadHandler; _thread.Start(); }
IEnumerator Move() { pinkRect.transform.DOLocalMoveX(250, 1.0f); yield return(new WaitForSeconds(1)); pinkRect.transform.DOLocalMoveY(-150, 2); yield return(new WaitForSeconds(2)); //AI操作,陷入深思,在异步线程执行,GreenRect不会卡顿 job.Start(); yield return(StartCoroutine(job.WaitFor())); pinkRect.transform.DOLocalMoveY(150, 2); }
protected virtual void Start(int numNodes, double runTimeSec, int maxSearcherAgeSeconds) { endTimeNanos = J2N.Time.NanoTime() + (long)(runTimeSec * 1000000000); this.maxSearcherAgeSeconds = maxSearcherAgeSeconds; m_nodes = new NodeState[numNodes]; for (int nodeID = 0; nodeID < numNodes; nodeID++) { m_nodes[nodeID] = new NodeState(this, Random, nodeID, numNodes); } long[] nodeVersions = new long[m_nodes.Length]; for (int nodeID = 0; nodeID < numNodes; nodeID++) { IndexSearcher s = m_nodes[nodeID].Mgr.Acquire(); try { nodeVersions[nodeID] = m_nodes[nodeID].Searchers.Record(s); } finally { m_nodes[nodeID].Mgr.Release(s); } } for (int nodeID = 0; nodeID < numNodes; nodeID++) { IndexSearcher s = m_nodes[nodeID].Mgr.Acquire(); if (Debugging.AssertsEnabled) { Debugging.Assert(nodeVersions[nodeID] == m_nodes[nodeID].Searchers.Record(s)); } if (Debugging.AssertsEnabled) { Debugging.Assert(s != null); } try { BroadcastNodeReopen(nodeID, nodeVersions[nodeID], s); } finally { m_nodes[nodeID].Mgr.Release(s); } } changeIndicesThread = new ChangeIndices(this); changeIndicesThread.Start(); }
internal string[] Next() { if (t == null) { threadDone = false; t = new ThreadJob(Run); t.IsBackground = true; t.Start(); } string[] result; UninterruptableMonitor.Enter(this); try { while (tuple == null && nmde == null && !threadDone && !stopped) { try { UninterruptableMonitor.Wait(this); } catch (Exception ie) when(ie.IsInterruptedException()) { throw new Util.ThreadInterruptedException(ie); } } if (tuple != null) { result = tuple; tuple = null; Monitor.Pulse(this);// notify(); return(result); } if (nmde != null) { // Set to null so we will re-start thread in case // we are re-used: t = null; throw nmde; } // The thread has exited yet did not hit end of // data, so this means it hit an exception. We // throw NoMorDataException here to force // benchmark to stop the current alg: throw new NoMoreDataException(); } finally { UninterruptableMonitor.Exit(this); } }
private IEnumerator LoadImageFromURLIntoImageSphereInternal(ImageSphereController imageSphereController, int sphereIndex, int postImageIndex, string url, string imageIdentifier, bool showLoading) { if (postImageIndex != Helper.kIgnoreImageIndex && !m_posts.IsValidRequest(postImageIndex)) { yield break; } yield return(m_appDirector.VerifyInternetConnection()); m_isLoading = true; if (showLoading) { m_loadingIcon.Display(); } if (Debug.isDebugBuild) { Debug.Log("------- VREEL: Downloading image and getting stream through GetImageStreamFromURL() with url: " + url); } yield return(m_threadJob.WaitFor()); bool debugOn = Debug.isDebugBuild; Stream imageStream = null; int contentLength = 0; m_threadJob.Start(() => contentLength = GetImageStreamFromURL(url, ref imageStream, debugOn) ); yield return(m_threadJob.WaitFor()); if (contentLength > 0) { int textureIndex = GetAvailableTextureIndex(); yield return(m_cppPlugin.LoadImageFromStreamIntoImageSphere(imageSphereController, sphereIndex, imageStream, imageIdentifier, textureIndex, contentLength)); imageStream.Close(); } else { imageSphereController.SetImageAtIndexToLoading(sphereIndex, true); } m_isLoading = false; if (showLoading) { m_loadingIcon.Hide(); } }
internal string[] Next() { if (t == null) { threadDone = false; t = new ThreadJob(Run); t.IsBackground = true; t.Start(); } string[] result; lock (this) { while (tuple == null && nmde == null && !threadDone && !stopped) { Monitor.Wait(this); // LUCENENET NOTE: No need to catch and rethrow same excepton type ThreadInterruptedException. Note that it could be thrown above on lock (this). } if (tuple != null) { result = tuple; tuple = null; Monitor.Pulse(this);// notify(); return(result); } if (nmde != null) { // Set to null so we will re-start thread in case // we are re-used: t = null; throw nmde; } // The thread has exited yet did not hit end of // data, so this means it hit an exception. We // throw NoMorDataException here to force // benchmark to stop the current alg: throw new NoMoreDataException(); } }
private IEnumerator OpenAndroidGalleryInternal() { Debug.Log("------- Texture2DTest: OpenAndroidGallery() called"); m_currPictureIndex = 0; m_pictureFilePaths.Clear(); string path = "/storage/emulated/0/DCIM/"; //HARDCODED: Hardcoded path, //this may need to be changed depending on device used Debug.Log("------- Texture2DTest: Storing all FilePaths from directory: " + path); bool foundJob = false; m_threadJob.Start(() => foundJob = StoreAllFilePaths(path) ); yield return(m_threadJob.WaitFor()); int numImageDisplays = m_imageDisplays.GetLength(0); LoadPictures(m_currPictureIndex, numImageDisplays); }
public virtual void TestIntermediateClose() { Directory dir = NewDirectory(); // Test can deadlock if we use SMS: IConcurrentMergeScheduler scheduler; #if !FEATURE_CONCURRENTMERGESCHEDULER scheduler = new TaskMergeScheduler(); #else scheduler = new ConcurrentMergeScheduler(); #endif IndexWriter writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetMergeScheduler(scheduler)); writer.AddDocument(new Document()); writer.Commit(); CountdownEvent awaitEnterWarm = new CountdownEvent(1); CountdownEvent awaitClose = new CountdownEvent(1); AtomicBoolean triedReopen = new AtomicBoolean(false); //TaskScheduler es = Random().NextBoolean() ? null : Executors.newCachedThreadPool(new NamedThreadFactory("testIntermediateClose")); TaskScheduler es = Random.NextBoolean() ? null : TaskScheduler.Default; SearcherFactory factory = new SearcherFactoryAnonymousInnerClassHelper2(this, awaitEnterWarm, awaitClose, triedReopen, es); SearcherManager searcherManager = Random.NextBoolean() ? new SearcherManager(dir, factory) : new SearcherManager(writer, Random.NextBoolean(), factory); if (Verbose) { Console.WriteLine("sm created"); } IndexSearcher searcher = searcherManager.Acquire(); try { assertEquals(1, searcher.IndexReader.NumDocs); } finally { searcherManager.Release(searcher); } writer.AddDocument(new Document()); writer.Commit(); AtomicBoolean success = new AtomicBoolean(false); Exception[] exc = new Exception[1]; ThreadJob thread = new ThreadJob(() => new RunnableAnonymousInnerClassHelper(this, triedReopen, searcherManager, success, exc).Run()); thread.Start(); if (Verbose) { Console.WriteLine("THREAD started"); } awaitEnterWarm.Wait(); if (Verbose) { Console.WriteLine("NOW call close"); } searcherManager.Dispose(); awaitClose.Signal(); thread.Join(); try { searcherManager.Acquire(); fail("already closed"); } #pragma warning disable 168 catch (ObjectDisposedException ex) #pragma warning restore 168 { // expected } assertFalse(success); assertTrue(triedReopen); assertNull("" + exc[0], exc[0]); writer.Dispose(); dir.Dispose(); //if (es != null) //{ // es.shutdown(); // es.awaitTermination(1, TimeUnit.SECONDS); //} }
public IEnumerator LoadImageFromPath(ThreadJob threadJob, GameObject[] imageDisplays, int imageIndex, string filePath) { yield return(new WaitForEndOfFrame()); Debug.Log("------- Texture2DTest: Calling LoadPicturesInternal() from filePath: " + filePath); StringBuilder filePathForCpp = new StringBuilder(filePath); Debug.Log("------- Texture2DTest: Calling LoadIntoWorkingMemoryFromImagePath(), on background thread!"); yield return(threadJob.WaitFor()); bool ranJobSuccessfully = false; threadJob.Start(() => ranJobSuccessfully = LoadIntoWorkingMemoryFromImagePath(filePathForCpp) ); yield return(threadJob.WaitFor()); Debug.Log("------- Texture2DTest: Finished LoadIntoWorkingMemoryFromImagePath(), ran Job Successully = " + ranJobSuccessfully); Debug.Log("------- Texture2DTest: Calling CreateEmptyTexture()"); yield return(new WaitForEndOfFrame()); GL.IssuePluginEvent(GetRenderEventFunc(), (int)RenderFunctions.kCreateEmptyTexture); yield return(new WaitForSeconds(kFrameWaitTime)); // These waits need to be longer to ensure that GL.IssuePluginEvent() has gone through! Debug.Log("------- Texture2DTest: Finished CreateEmptyTexture(), Texture Handle = " + GetCurrStoredTexturePtr()); Debug.Log("------- Texture2DTest: Calling LoadScanlinesIntoTextureFromWorkingMemory()"); while (IsLoadingIntoTexture()) { GL.IssuePluginEvent(GetRenderEventFunc(), (int)RenderFunctions.kLoadScanlinesIntoTextureFromWorkingMemory); yield return(new WaitForSeconds(kFrameWaitTime)); } Debug.Log("------- Texture2DTest: Finished LoadScanlinesIntoTextureFromWorkingMemory()"); Debug.Log("------- Texture2DTest: Calling CreateExternalTexture(), size of Texture is Width x Height = " + GetCurrStoredImageWidth() + " x " + GetCurrStoredImageHeight()); yield return(new WaitForEndOfFrame()); Texture2D newTexture = Texture2D.CreateExternalTexture( GetCurrStoredImageWidth(), GetCurrStoredImageHeight(), TextureFormat.RGBA32, // Default textures have a format of ARGB32 false, false, GetCurrStoredTexturePtr() ); yield return(new WaitForEndOfFrame()); Debug.Log("------- Texture2DTest: Finished CreateExternalTexture()!"); Debug.Log("------- Texture2DTest: Calling SetImageAndFilePath()"); imageDisplays[imageIndex].GetComponent <SelectImage>().SetImageAndFilePath(newTexture, filePath); yield return(new WaitForEndOfFrame()); Debug.Log("------- Texture2DTest: Finished SetImageAndFilePath()"); Resources.UnloadUnusedAssets(); }
public IEnumerator LoadImageFromPathIntoImageSphere(ImageSphereController imageSphereController, int sphereIndex, string filePathAndIdentifier, int textureIndex, int maxImageWidth) { StringBuilder filePathForCpp = new StringBuilder(filePathAndIdentifier); if (Debug.isDebugBuild) { Debug.Log("------- VREEL: Calling LoadImageFromPathIntoImageSphere() with sphereIndex : " + sphereIndex + ", from filePath: " + filePathAndIdentifier + ", with TextureIndex: " + textureIndex + ", with MaxImageWidth: " + maxImageWidth); } yield return(null); SetRGB565On(Helper.kRGB565On); SetMaxImageWidth(maxImageWidth); SetUseExif(false); //SetUseExif(maxImageWidth == Helper.kThumbnailWidth); //if (Debug.isDebugBuild) Debug.Log("------- VREEL: Calling LoadIntoWorkingMemoryFromImagePath(), on background thread!"); yield return(m_threadJob.WaitFor()); bool ranJobSuccessfully = false; m_threadJob.Start(() => ranJobSuccessfully = LoadIntoWorkingMemoryFromImagePath(filePathForCpp) ); yield return(m_threadJob.WaitFor()); //if (Debug.isDebugBuild) Debug.Log("------- VREEL: Finished LoadIntoWorkingMemoryFromImagePath(), ran Job Successully = " + ranJobSuccessfully); //TODO: Make CreateEmptyTexture() more efficient - the problem is simply that a glTexImage2D() call is slow with large textures! //if (Debug.isDebugBuild) Debug.Log("------- VREEL: Calling CreateEmptyTexture() over textureIndex = " + textureIndex); yield return(m_waitForEndOfFrame); SetCurrTextureIndex(textureIndex); GL.IssuePluginEvent(GetRenderEventFunc(), (int)RenderFunctions.kRenewTextureHandle); yield return(m_waitForSeconds); // These waits need to be longer to ensure that GL.IssuePluginEvent() has gone through! yield return(null); GL.IssuePluginEvent(GetRenderEventFunc(), (int)RenderFunctions.kCreateEmptyTexture); yield return(m_waitForSeconds); // These waits need to be longer to ensure that GL.IssuePluginEvent() has gone through! //if (Debug.isDebugBuild) Debug.Log("------- VREEL: Finished CreateEmptyTexture(), Texture Handle = " + GetCurrStoredTexturePtr() ); //if (Debug.isDebugBuild) Debug.Log("------- VREEL: Calling LoadScanlinesIntoTextureFromWorkingMemory()"); while (IsLoadingIntoTexture()) { yield return(m_waitForEndOfFrame); GL.IssuePluginEvent(GetRenderEventFunc(), (int)RenderFunctions.kLoadScanlinesIntoTextureFromWorkingMemory); yield return(m_waitForSeconds); } //if (Debug.isDebugBuild) Debug.Log("------- VREEL: Finished LoadScanlinesIntoTextureFromWorkingMemory()"); //if (Debug.isDebugBuild) Debug.Log("------- VREEL: Calling CreateExternalTexture(), size of Texture is Width x Height = " + GetCurrStoredImageWidth() + " x " + GetCurrStoredImageHeight()); yield return(m_waitForEndOfFrame); m_lastTextureOperatedOn = Texture2D.CreateExternalTexture( GetCurrStoredImageWidth(), GetCurrStoredImageHeight(), Helper.kRGB565On ? TextureFormat.RGB565 : TextureFormat.RGB24, // Default textures have a format of ARGB32 true, true, GetCurrStoredTexturePtr() ); yield return(null); m_lastTextureOperatedOn.filterMode = FilterMode.Trilinear; //if (Debug.isDebugBuild) Debug.Log("------- VREEL: Finished CreateExternalTexture()!"); //if (Debug.isDebugBuild) Debug.Log("------- VREEL: Calling SetImageAtIndex()"); imageSphereController.SetImageAtIndex(sphereIndex, m_lastTextureOperatedOn, filePathAndIdentifier, textureIndex, true); //if (Debug.isDebugBuild) Debug.Log("------- VREEL: Finished SetImageAtIndex()"); if (Debug.isDebugBuild) { Debug.Log("------- VREEL: Completed LoadImageFromPathIntoImageSphere() with sphereIndex : " + sphereIndex + ", from filePath: " + filePathAndIdentifier + ", with TextureIndex: " + textureIndex); } }
private IEnumerator UploadImageInternal(string filePath, bool profilePic = false) //NOTE: Ensured that this function cannot be stopped midway because the LoadingIcon blocks UI { yield return(m_appDirector.VerifyInternetConnection()); m_loadingIcon.Display(); if (Debug.isDebugBuild) { Debug.Log("------- VREEL: Running UploadImageInternal() for image with path: " + filePath); } //0) Delete temporary file's if they somehow still exist... string originalImageFilePath = filePath; string tempThumbnailPath = m_imagesTopLevelDirectory + "/tempThumbnailImage.png"; string tempOriginalPath = m_imagesTopLevelDirectory + "/tempOriginalImage.png"; if (File.Exists(tempThumbnailPath)) { File.Delete(tempThumbnailPath); } if (File.Exists(tempOriginalPath)) { File.Delete(tempOriginalPath); } // 1) Get PresignedURL yield return(m_backEndAPI.S3_PresignedURL()); // 2) Create Thumbnail from Original image bool successfullyCreatedThumbnail = false; bool successfullyCreatedMaxResolutionImage = false; if (m_backEndAPI.IsLastAPICallSuccessful()) { bool isDebugBuild = Debug.isDebugBuild; m_threadJob.Start(() => successfullyCreatedThumbnail = CreateSmallerImageWithResolution(originalImageFilePath, tempThumbnailPath, Helper.kThumbnailWidth, isDebugBuild) ); yield return(m_threadJob.WaitFor()); m_threadJob.Start(() => successfullyCreatedMaxResolutionImage = CreateSmallerImageWithResolution(originalImageFilePath, tempOriginalPath, Helper.kMaxImageWidth, isDebugBuild) ); yield return(m_threadJob.WaitFor()); } // 3) Upload Original if (m_backEndAPI.IsLastAPICallSuccessful() && successfullyCreatedThumbnail && successfullyCreatedMaxResolutionImage) { yield return(m_backEndAPI.UploadObject( m_backEndAPI.GetS3PresignedURLResult().data.attributes.original.url.ToString(), originalImageFilePath )); } // 4) Upload Thumbnail if (m_backEndAPI.IsLastAPICallSuccessful() && successfullyCreatedThumbnail && successfullyCreatedMaxResolutionImage) { yield return(m_backEndAPI.UploadObject( m_backEndAPI.GetS3PresignedURLResult().data.attributes.thumbnail.url.ToString(), tempThumbnailPath )); } // 5) Register Post as Created if (m_backEndAPI.IsLastAPICallSuccessful() && successfullyCreatedThumbnail && successfullyCreatedMaxResolutionImage) { string captionText = m_captionNewText.GetComponentInChildren <Text>().text; Helper.TruncateString(ref captionText, Helper.kMaxCaptionOrDescriptionLength); if (profilePic) { yield return(m_backEndAPI.Register_UpdateProfileImage( m_backEndAPI.GetS3PresignedURLResult().data.attributes.thumbnail.key.ToString(), m_backEndAPI.GetS3PresignedURLResult().data.attributes.original.key.ToString() )); } else { yield return(m_backEndAPI.Post_CreatePost( m_backEndAPI.GetS3PresignedURLResult().data.attributes.thumbnail.key.ToString(), m_backEndAPI.GetS3PresignedURLResult().data.attributes.original.key.ToString(), captionText )); } } //6) Delete temporary thumbnail file if (successfullyCreatedThumbnail) { File.Delete(tempThumbnailPath); } if (successfullyCreatedMaxResolutionImage) { File.Delete(tempOriginalPath); } yield return(null); // 7) If there has been a successful upload -> Inform user that image has been uploaded if (Debug.isDebugBuild) { Debug.Log("------- VREEL: Uploaded image: " + originalImageFilePath + ", with Success: " + (m_backEndAPI.IsLastAPICallSuccessful() && successfullyCreatedThumbnail && successfullyCreatedMaxResolutionImage)); } if (m_backEndAPI.IsLastAPICallSuccessful()) { //TODO: SHOW A SUCCESS MESSAGE! } m_imageFlow.Close(); m_loadingIcon.Hide(); if (profilePic) { m_profile.SetMenuBarProfileDetails(); } }