System.Threading.ThreadPool.QueueUserWorkItem(System.Threading.WaitCallback)

Here are the examples of the csharp api System.Threading.ThreadPool.QueueUserWorkItem(System.Threading.WaitCallback) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1039 Examples 7

19 Source : WebSocketServer.cs
with GNU General Public License v2.0
from Cdorey

private void receiveRequest ()
    {
      while (true) {
        TcpClient cl = null;
        try {
          cl = _listener.AcceptTcpClient ();
          ThreadPool.QueueUserWorkItem (
            state => {
              try {
                var ctx = new TcpListenerWebSocketContext (
                            cl, null, _secure, _sslConfigInUse, _log
                          );

                if (!ctx.Authenticate (_authSchemes, _realmInUse, _userCredFinder))
                  return;

                processRequest (ctx);
              }
              catch (Exception ex) {
                _log.Error (ex.Message);
                _log.Debug (ex.ToString ());

                cl.Close ();
              }
            }
          );
        }
        catch (SocketException ex) {
          if (_state == ServerState.ShuttingDown) {
            _log.Info ("The underlying listener is stopped.");
            break;
          }

          _log.Fatal (ex.Message);
          _log.Debug (ex.ToString ());

          break;
        }
        catch (Exception ex) {
          _log.Fatal (ex.Message);
          _log.Debug (ex.ToString ());

          if (cl != null)
            cl.Close ();

          break;
        }
      }

      if (_state != ServerState.ShuttingDown)
        abort ();
    }

19 Source : UpdateProcess.cs
with Apache License 2.0
from chancezheng

public bool CheckAppVersion()
        {
            bool isNeedUpdate = false;
            string httpAddress = MedicalReportViewModel.GetBinPath() + "\\AutoUpdate\\updateinfo.xml";
            string currentVersion = replacedembly.GetExecutingreplacedembly().GetName().Version.ToString();
            ThreadPool.QueueUserWorkItem(q =>
            {
                var client = new WebClient();
                client.DownloadDataCompleted += (obj, e) =>
                {
                    try
                    {
                        MemoryStream ms = new MemoryStream(e.Result);

                        UpdateInfo updateInfo = new UpdateInfo();
                        XDoreplacedent doreplacedent = XDoreplacedent.Load(ms);
                        XElement rootElement = doreplacedent.Element("UpdateInfo");
                        updateInfo.AppName = rootElement.Element("AppName").Value;
                        updateInfo.AppVersion = rootElement.Element("AppVersion") == null || string.IsNullOrEmpty(rootElement.Element("AppVersion").Value) ? null : new Version(rootElement.Element("AppVersion").Value);
                        updateInfo.RequiredMinVersion = rootElement.Element("RequiredMinVersion") == null || string.IsNullOrEmpty(rootElement.Element("RequiredMinVersion").Value) ? null : new Version(rootElement.Element("RequiredMinVersion").Value);
                        updateInfo.Description = rootElement.Element("Description").Value;
                        updateInfo.MD5 = Guid.NewGuid();

                        ms.Close();
                        isNeedUpdate = StartUpdate(updateInfo);
                        if (isNeedUpdate)
                        {
                            //启动更新程序
                            Process.Start(Directory.GetCurrentDirectory() + "\\AppUpdate\\netcoreapp3.1\\AutoUpdatedApp.exe");

                            foreach (var process in Process.GetProcessesByName(AppExeName))
                            {
                                process.Kill();
                            }

                            isNeedUpdate = false;
                        }
                    }
                    catch (Exception ex)
                    {
                        Trace.WriteLine(ex.Message);
                    }
                };
                client.DownloadDataAsync(new Uri(httpAddress, UriKind.Absolute));
            });

            return isNeedUpdate;
        }

19 Source : SIPSorcerySMTP.cs
with MIT License
from chatop2020

public static void SendEmail(string toAddress, string fromAddress, string subject, string messageBody)
        {
            ThreadPool.QueueUserWorkItem(delegate
            {
                SendEmailAsync(toAddress, fromAddress, null, null, subject, messageBody);
            });
        }

19 Source : SIPSorcerySMTP.cs
with MIT License
from chatop2020

public static void SendEmail(string toAddress, string fromAddress, string ccAddress, string bccAddress,
            string subject, string messageBody)
        {
            ThreadPool.QueueUserWorkItem(delegate
            {
                SendEmailAsync(toAddress, fromAddress, ccAddress, bccAddress, subject, messageBody);
            });
        }

19 Source : SIPRegistrationUserAgent.cs
with MIT License
from chatop2020

public void Stop(bool sendZeroExpiryRegister = true)
        {
            try
            {
                if (!m_exit)
                {
                    logger.LogDebug($"Stopping SIP registration user agent for {m_sipAccountAOR}.");

                    m_exit = true;
                    m_waitForRegistrationMRE.Set();

                    if (m_isRegistered && sendZeroExpiryRegister)
                    {
                        m_attempts = 0;
                        m_expiry = 0;
                        ThreadPool.QueueUserWorkItem(delegate { SendInitialRegister(); });
                    }

                    m_registrationTimer.Dispose();
                    m_registrationTimer = null;
                }
            }
            catch (Exception excp)
            {
                logger.LogError("Exception SIPRegistrationUserAgent Stop. " + excp.Message);
            }
        }

19 Source : SIPNotifierClient.cs
with MIT License
from chatop2020

public void Start()
        {
            m_exit = false;

            m_sipTransport.SIPTransportRequestReceived += GotNotificationRequest;

            ThreadPool.QueueUserWorkItem(delegate { StartSubscription(); });
        }

19 Source : SIPNotifierClient.cs
with MIT License
from chatop2020

public void Stop()
        {
            try
            {
                if (!m_exit)
                {
                    logger.LogDebug($"Stopping SIP notifier user agent for user {m_authUsername} and resource URI {m_resourceURI}.");

                    m_exit = true;
                    m_attempts = 0;

                    m_sipTransport.SIPTransportRequestReceived -= GotNotificationRequest;

                    ThreadPool.QueueUserWorkItem(delegate
                    { Subscribe(m_resourceURI, 0, m_sipEventPackage, m_subscribeCallID, null); });
                }
            }
            catch (Exception excp)
            {
                logger.LogError("Exception SIPNotifierClient Stop. " + excp.Message);
            }
        }

19 Source : RTSPClient.cs
with MIT License
from chatop2020

public void Play()
        {
            ThreadPool.QueueUserWorkItem(delegate
            { ProcessRTPPackets(); });
            ThreadPool.QueueUserWorkItem(delegate
            { SendKeepAlives(); });

            RTSPRequest playRequest = new RTSPRequest(RTSPMethodsEnum.PLAY, _url);
            RTSPHeader playHeader = new RTSPHeader(_cseq++, _rtspSession.SessionID);
            playRequest.Header = playHeader;

            System.Diagnostics.Debug.WriteLine(playRequest.ToString());

            var rtspRequestBuffer = Encoding.UTF8.GetBytes(playRequest.ToString());
            _rtspStream.Write(rtspRequestBuffer, 0, rtspRequestBuffer.Length);

            var buffer = new byte[2048];
            var bytesRead = _rtspStream.Read(buffer, 0, 2048);

            if (bytesRead > 0)
            {
                System.Diagnostics.Debug.WriteLine(Encoding.UTF8.GetString(buffer, 0, bytesRead));

                var rtspMessage = RTSPMessage.ParseRTSPMessage(buffer, null, null);

                if (rtspMessage.RTSPMessageType == RTSPMessageTypesEnum.Response)
                {
                    var playResponse = RTSPResponse.ParseRTSPResponse(rtspMessage);
                    logger.LogDebug("RTSP Response received to PLAY: " + playResponse.StatusCode + " " + playResponse.Status + " " + playResponse.ReasonPhrase + ".");
                }
            }
            else
            {
                throw new ApplicationException("Zero bytes were read from the RTSP client socket in response to a PLAY request.");
            }
        }

19 Source : RTSPServer.cs
with MIT License
from chatop2020

private void Initialise()
        {
            try
            {
                m_tcpServerListener = new TcpListener(m_localIPEndPoint);

                m_tcpServerListener.Start(MAX_TCP_CONNECTIONS);

                ThreadPool.QueueUserWorkItem(delegate
                { AcceptConnections(ACCEPT_THREAD_NAME + m_localIPEndPoint.Port); });
                ThreadPool.QueueUserWorkItem(delegate
                { PruneConnections(PRUNE_THREAD_NAME + m_localIPEndPoint.Port); });

                logger.LogDebug("RTSP server listener created " + m_localIPEndPoint + ".");
            }
            catch (Exception excp)
            {
                logger.LogError("Exception RTSPServer Initialise. " + excp.Message);
                throw excp;
            }
        }

19 Source : SchedulerService.cs
with Apache License 2.0
from chkr1011

void UpdateActiveCountdowns(TimeSpan elapsed)
        {
            lock (_activeCountdowns)
            {
                var activeCountdowns = _activeCountdowns.ToList();

                foreach (var activeCountdown in activeCountdowns)
                {
                    activeCountdown.Value.TimeLeft -= elapsed;

                    if (activeCountdown.Value.TimeLeft > TimeSpan.Zero)
                    {
                        continue;
                    }

                    _activeCountdowns.Remove(activeCountdown.Key);
                    _logger.LogTrace($"Countdown '{activeCountdown.Key}' elapsed. Invoking callback.");

                    ThreadPool.QueueUserWorkItem(_ =>
                    {
                        try
                        {
                            activeCountdown.Value.Callback.Invoke(new CountdownElapsedParameters(activeCountdown.Key, activeCountdown.Value.State));
                        }
                        catch (Exception exception)
                        {
                            _logger.LogError(exception, $"Error while executing callback of countdown '{activeCountdown.Key}'.");
                        }
                    });
                }
            }
        }

19 Source : Program.cs
with MIT License
from chronoxor

protected override void OnReceived(EndPoint endpoint, byte[] buffer, long offset, long size)
        {
            Program.TimestampStop = DateTime.UtcNow;
            Program.TotalBytes += size;
            Program.TotalMessages++;

            // Continue receive datagrams
            // Important: Receive using thread pool is necessary here to avoid stack overflow with Socket.ReceiveFromAsync() method!
            ThreadPool.QueueUserWorkItem(o => { ReceiveAsync(); } );

            SendMessage();
        }

19 Source : Program.cs
with MIT License
from chronoxor

protected override void OnReceived(EndPoint endpoint, byte[] buffer, long offset, long size)
        {
            // Continue receive datagrams.
            if (size == 0)
            {
                // Important: Receive using thread pool is necessary here to avoid stack overflow with Socket.ReceiveFromAsync() method!
                ThreadPool.QueueUserWorkItem(o => { ReceiveAsync(); });
            }

            // Echo the message back to the sender
            SendAsync(endpoint, buffer, offset, size);
        }

19 Source : Program.cs
with MIT License
from chronoxor

protected override void OnSent(EndPoint endpoint, long sent)
        {
            // Continue receive datagrams.
            // Important: Receive using thread pool is necessary here to avoid stack overflow with Socket.ReceiveFromAsync() method!
            ThreadPool.QueueUserWorkItem(o => { ReceiveAsync(); } );
        }

19 Source : UdpTests.cs
with MIT License
from chronoxor

protected override void OnSent(EndPoint endpoint, long sent) { ThreadPool.QueueUserWorkItem(o => { ReceiveAsync(); } ); }

19 Source : TMP_PackageUtilities.cs
with MIT License
from chstetco

private IEnumerator ScanProjectFiles()
        {
            m_IsAlreadyScanningProject = true;
            string packageFullPath = EditorUtilities.TMP_EditorUtility.packageFullPath;

            // List containing replacedets that have been modified.
            m_ProjectScanResults = k_ProjectScanReportDefaultText;
            m_ModifiedreplacedetList.Clear();
            m_ProgressPercentage = 0;

            // Read Conversion Data from Json file.
            if (m_ConversionData == null)
                m_ConversionData = JsonUtility.FromJson<replacedetConversionData>(File.ReadAllText(packageFullPath + "/PackageConversionData.json"));

            // Get list of GUIDs for replacedets that might contain references to previous GUIDs that require updating.
            string searchFolder = string.IsNullOrEmpty(m_ProjectFolderToScan) ? "replacedets" : ("replacedets/" + m_ProjectFolderToScan);
            string[] guids = replacedetDatabase.Findreplacedets("t:Object", new string[] { searchFolder }).Distinct().ToArray();

            k_ProjectScanLabelPrefix = "<b>Phase 1 - Filtering:</b> ";
            m_ScanningTotalFiles = guids.Length;
            m_ScanningCurrentFileIndex = 0;

            List<replacedetFileRecord> projectFilesToScan = new List<replacedetFileRecord>();

            foreach (var guid in guids)
            {
                if (m_CancelScanProcess)
                    break;

                string replacedetFilePath = replacedetDatabase.GUIDToreplacedetPath(guid);

                m_ScanningCurrentFileIndex += 1;
                m_ScanningCurrentFileName = replacedetFilePath;
                m_ProgressPercentage = (float)m_ScanningCurrentFileIndex / m_ScanningTotalFiles;

                // Filter out file types we have no interest in searching
                if (ShouldIgnoreFile(replacedetFilePath))
                    continue;

                string replacedetMetaFilePath = replacedetDatabase.GetTextMetaFilePathFromreplacedetPath(replacedetFilePath);

                projectFilesToScan.Add(new replacedetFileRecord(replacedetFilePath, replacedetMetaFilePath));

                yield return null;
            }

            m_RemainingFilesToScan = m_ScanningTotalFiles = projectFilesToScan.Count;

            k_ProjectScanLabelPrefix = "<b>Phase 2 - Scanning:</b> ";

            for (int i = 0; i < m_ScanningTotalFiles; i++)
            {
                if (m_CancelScanProcess)
                    break;

                replacedetFileRecord fileRecord = projectFilesToScan[i];

                ThreadPool.QueueUserWorkItem(Task =>
                {
                    ScanProjectFileAsync(fileRecord);

                    m_ScanningCurrentFileName = fileRecord.replacedetFilePath;

                    int completedScans = m_ScanningTotalFiles - Interlocked.Decrement(ref m_RemainingFilesToScan);

                    m_ScanningCurrentFileIndex = completedScans;
                    m_ProgressPercentage = (float)completedScans / m_ScanningTotalFiles;
                });

                if (i % 64 == 0)
                    yield return new WaitForSeconds(2.0f);

            }

            while (m_RemainingFilesToScan > 0 && !m_CancelScanProcess)
                yield return null;

            m_IsAlreadyScanningProject = false;
            m_ScanningCurrentFileName = string.Empty;
        }

19 Source : ShellObjectFactory.cs
with GNU General Public License v3.0
from CitizensReactor

private static bool IsVirtualKnownFolder(IShellItem2 nativeShellItem2)
        {
            IntPtr pidl = IntPtr.Zero;
            try
            {
                IKnownFolderNative nativeFolder = null;
                KnownFoldersSafeNativeMethods.NativeFolderDefinition definition = new KnownFoldersSafeNativeMethods.NativeFolderDefinition();

                // We found a bug where the enumeration of shell folders was
                // not reliable when called from a STA thread - it would return
                // different results the first time vs the other times.
                //
                // This is a work around.  We call FindFolderFromIDList on a
                // worker MTA thread instead of the main STA thread.
                //
                // Ultimately, it would be a very good idea to replace the 'getting shell object' logic
                // to get a list of pidl's in 1 step, then look up their information in a 2nd, rather than
                // looking them up as we get them.  This would replace the need for the work around.
                object padlock = new object();
                lock (padlock)
                {
                    IntPtr unknown = Marshal.GetIUnknownForObject(nativeShellItem2);

                    ThreadPool.QueueUserWorkItem(obj =>
                    {
                        lock (padlock)
                        {
                            pidl = ShellHelper.PidlFromUnknown(unknown);

                            new KnownFolderManagerClreplaced().FindFolderFromIDList(pidl, out nativeFolder);

                            if (nativeFolder != null)
                            {
                                nativeFolder.GetFolderDefinition(out definition);
                            }

                            Monitor.Pulse(padlock);
                        }
                    });

                    Monitor.Wait(padlock);
                }

                return nativeFolder != null && definition.category == FolderCategory.Virtual;
            }
            finally
            {
                ShellNativeMethods.ILFree(pidl);
            }
        }

19 Source : WeChatSDK.cs
with MIT License
from cixingguangming55555

async void StartReceiving(ClientWebSocket client)
        {
            if (client is null) client = WeChatHelper;
            string _result = "";
            while (true)
            {
                Trace.WriteLine(String.Format("在线程[{0}]收到消息.", Thread.CurrentThread.ManagedThreadId.ToString()));
                var array = new byte[4096];
                var result = await client.ReceiveAsync(new ArraySegment<byte>(array), CancellationToken.None);

                if (result.MessageType == WebSocketMessageType.Text)
                {

                    Trace.WriteLine(String.Format("[{0}]Client Status:{1}.",DateTime.Now.ToString(),client.State.ToString()));
                    Trace.WriteLine(String.Format("[{0}]收到:{1}.",DateTime.Now.ToString(),_result));
                    string msg = Encoding.UTF8.GetString(array, 0, result.Count);
                    if (result.EndOfMessage)
                    {
                        _result += msg;
                        baseRecMessage = _result;
                        var _json = JObject.Parse(_result);
                        switch (_json["type"].ToString().ToLower())
                        {
                            case "1"://文本消息
                            case "3"://图片消息
                                RecMessage.Enqueue(_result);
                                break;
                            case "5001"://获取联系人及群消息类型,一个群也相当于一个联系人
                                if (UpDataLog.ContainsKey("USERLIST"))
                                {
                                    UpDataLog["USERLIST"] = GetTimeStamp();
                                }
                                else
                                {
                                    UpDataLog.Add("USERLIST", GetTimeStamp());
                                }
                                USERLIST = _result;
                                Trace.WriteLine(String.Format("获取通讯录列表完成,[{0}]", _result));
                                new Thread(new ThreadStart(RefreshContactList));
                                break;
                            case "5005"://WebSocket心跳消息
                                RecMessage.Enqueue(_result);
                                Trace.WriteLine(String.Format("[{0}]WebSocket connection is onlive.",DateTime.Now.ToString()));
                                break;
                            case "5010"://获取群成员返回消息类型
                            case "5020":
                                CHATROOMINFO = _result;
                                ThreadPool.QueueUserWorkItem(p=>{
                                    RefreshChatRoomUser(CHATROOMINFO);
                                });
                                break;
                            case "6000"://调试信息开关
                                DEBUGINFO = _result;
                                break;
                            case "6500"://获取个人信息
                            case "6550"://获取个人信息
                                USERINFO = _result;
                                ThreadPool.QueueUserWorkItem(p => {
                                    FormatUserInfo(USERINFO);
                                });
                                break;
                            default:
                                RecMessage.Enqueue(_result);
                                break;
                        };
                        _result = null;
                    }
                    else
                    {
                        _result += msg;
                    }
                }
                Thread.Sleep(Wait_for_Receive_Messages);
            }
        }

19 Source : TestDispatcher.cs
with MIT License
from Const-me

public static void test()
		{
			createEngine( out var engine );
			engine.setConsoleLoggerSink( eLogLevel.Debug );

			using( mainDispatcher = engine.dispatcher() )
			{
				ThreadPool.QueueUserWorkItem( readKey );

				Console.WriteLine( "{0} Created the dispatcher", id );
				mainDispatcher.run();
			}

			Console.WriteLine( "{0} The dispatcher quit normally", id );
		}

19 Source : SampleRenderer.cs
with MIT License
from Const-me

static void runFullScreen( iGraphicsEngine engine, SampleBase sample )
		{
			iVideoSetup videoSetup = new Utils.VideoSetup( idealDrmFormat );
			var dispatcher = engine.dispatcher();
			ThreadPool.QueueUserWorkItem( obj => { Console.ReadKey(); dispatcher.postQuitMessage( 0 ); } );

			engine.renderFullScreen( sample.context, fullscreenResolution, videoSetup );
		}

19 Source : Tesselator.post.cs
with MIT License
from Const-me

iTessellatedMeshes updateOldJob( Meshes meshes, ref Options options )
		{
			Debug.replacedert( !options.separateStrokeMesh );

			lock( queues.syncRoot )
			{
				Options prevOptions = meshes.options;
				if( prevOptions.isGoodEnough( ref options ) && meshes.hasPolylines )
					return meshes;
				meshes.options = options;
				queues.enqueue( meshes );
				if( threadsRunning >= countThreads )
					return meshes;
				threadsRunning++;
			}
			ThreadPool.QueueUserWorkItem( postJobCallback );
			return meshes;
		}

19 Source : Tesselator.post.cs
with MIT License
from Const-me

iTessellatedMeshes createNewJob( Meshes meshes, ref Options options )
		{
			Debug.replacedert( !options.separateStrokeMesh );

			meshes.options = options;

			lock( queues.syncRoot )
			{
				queues.enqueue( meshes );
				if( threadsRunning >= countThreads )
					return meshes;
				threadsRunning++;
			}

			ThreadPool.QueueUserWorkItem( postJobCallback );
			return meshes;
		}

19 Source : Tesselator.post2.cs
with MIT License
from Const-me

(iTessellatedMeshes, iTessellatedMeshes) updateOldJobSeparate( Meshes meshes, ref Options options )
		{
			Debug.replacedert( options.separateStrokeMesh );

			lock( queues.syncRoot )
			{
				Options prevOptions = meshes.options;
				if( prevOptions.isGoodEnough( ref options ) && meshes.hasPolylines )
					return (meshes, meshes.extraStroke);
				meshes.options = options;
				meshes.ensureExtraStroke( factory );
				queues.enqueue( meshes );
				if( threadsRunning >= countThreads )
					return (meshes, meshes.extraStroke);
				threadsRunning++;
			}
			ThreadPool.QueueUserWorkItem( postJobCallback );
			return (meshes, meshes.extraStroke);
		}

19 Source : Tesselator.post2.cs
with MIT License
from Const-me

(iTessellatedMeshes, iTessellatedMeshes) createNewJobSeparate( Meshes meshes, ref Options options )
		{
			Debug.replacedert( options.separateStrokeMesh );

			meshes.options = options;
			meshes.ensureExtraStroke( factory );

			lock( queues.syncRoot )
			{
				queues.enqueue( meshes );
				if( threadsRunning >= countThreads )
					return (meshes, meshes.extraStroke);
				threadsRunning++;
			}

			ThreadPool.QueueUserWorkItem( postJobCallback );
			return (meshes, meshes.extraStroke);
		}

19 Source : Utils.cs
with Apache License 2.0
from cosmos-loops

public static void PostResult<T>(this TaskCompletionSource<T> k, T result) {
            ThreadPool.QueueUserWorkItem(notUsed => k.SetResult(result));
        }

19 Source : Utils.cs
with Apache License 2.0
from cosmos-loops

public static void PostException<T>(this TaskCompletionSource<T> k, Exception exc) {
            ThreadPool.QueueUserWorkItem(notUsed => k.SetException(exc));
        }

19 Source : Utils.cs
with Apache License 2.0
from cosmos-loops

public static void PostCancellation<T>(this TaskCompletionSource<T> k) {
            ThreadPool.QueueUserWorkItem(notUsed => k.SetCanceled());
        }

19 Source : Utils.cs
with Apache License 2.0
from cosmos-loops

public static void PostRegistration(this CancellationToken ct, Action<CancellationTokenRegistration> setRegistration, Action callback) {
            ThreadPool.QueueUserWorkItem
            (
                notUsed => {
                    CancellationTokenRegistration ctr = ct.Register
                    (
                        () => {
                            ThreadPool.QueueUserWorkItem
                            (
                                notUsed2 => { callback(); }
                            );
                        }
                    );
                    setRegistration(ctr);
                }
            );
        }

19 Source : Utils.cs
with Apache License 2.0
from cosmos-loops

public static Task PostContinueWith<T>(this Task<T> task, Action<Task<T>> action) {
            TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();

            task.ContinueWith
            (
                task2 => {
                    ThreadPool.QueueUserWorkItem
                    (
                        obj => {
                            try {
                                action(task2);
                                tcs.SetResult(true);
                            } catch (Exception exc) {
                                tcs.SetException(exc);
                            }
                        }
                    );
                },
                TaskContinuationOptions.None
            );

            return tcs.Task;
        }

19 Source : Utils.cs
with Apache License 2.0
from cosmos-loops

public static void PostDispose(this CancellationTokenRegistration ctr) {
            ThreadPool.QueueUserWorkItem
            (
                obj => { ctr.Dispose(); }
            );
        }

19 Source : AzurePushNotificationManager.android.cs
with MIT License
from CrossGeeks

public static void Initialize(Context context, string notificationHubConnectionString, string notificationHubPath, bool resetToken, bool createDefaultNotificationChannel = true, bool autoRegistration = true)
        {
            TokenKey = $"{notificationHubPath}_Token";
            RegisteredKey = $"{notificationHubPath}_PushRegistered";

            Hub = new NotificationHub(notificationHubPath, notificationHubConnectionString, Android.App.Application.Context);
      
            _context = context;

            CrossAzurePushNotification.Current.NotificationHandler = CrossAzurePushNotification.Current.NotificationHandler ?? new DefaultPushNotificationHandler();
            FirebaseMessaging.Instance.AutoInitEnabled = autoRegistration;
            if (autoRegistration)
            {
                ThreadPool.QueueUserWorkItem(state =>
                {

                    var packageName = Application.Context.PackageManager.GetPackageInfo(Application.Context.PackageName, PackageInfoFlags.MetaData).PackageName;
                    var versionCode = Application.Context.PackageManager.GetPackageInfo(Application.Context.PackageName, PackageInfoFlags.MetaData).VersionCode;
                    var versionName = Application.Context.PackageManager.GetPackageInfo(Application.Context.PackageName, PackageInfoFlags.MetaData).VersionName;
                    var prefs = Android.App.Application.Context.GetSharedPreferences(AzurePushNotificationManager.KeyGroupName, FileCreationMode.Private);

                    try
                    {

                        var storedVersionName = prefs.GetString(AzurePushNotificationManager.AppVersionNameKey, string.Empty);
                        var storedVersionCode = prefs.GetString(AzurePushNotificationManager.AppVersionCodeKey, string.Empty);
                        var storedPackageName = prefs.GetString(AzurePushNotificationManager.AppVersionPackageNameKey, string.Empty);


                        if (!CrossAzurePushNotification.Current.IsRegistered || resetToken || (!string.IsNullOrEmpty(storedPackageName) && (!storedPackageName.Equals(packageName, StringComparison.CurrentCultureIgnoreCase) || !storedVersionName.Equals(versionName, StringComparison.CurrentCultureIgnoreCase) || !storedVersionCode.Equals($"{versionCode}", StringComparison.CurrentCultureIgnoreCase))))
                        {
                            ((AzurePushNotificationManager)CrossAzurePushNotification.Current).CleanUp(false);

                        }

                    }
                    catch (Exception ex)
                    {
                        _onNotificationError?.Invoke(CrossAzurePushNotification.Current, new AzurePushNotificationErrorEventArgs(AzurePushNotificationErrorType.UnregistrationFailed, ex.ToString()));
                    }
                    finally
                    {
                        var editor = prefs.Edit();
                        editor.PutString(AzurePushNotificationManager.AppVersionNameKey, $"{versionName}");
                        editor.PutString(AzurePushNotificationManager.AppVersionCodeKey, $"{versionCode}");
                        editor.PutString(AzurePushNotificationManager.AppVersionPackageNameKey, $"{packageName}");
                        editor.Commit();
                    }


                    CrossAzurePushNotification.Current.RegisterForPushNotifications();


                });
            }
           

            if (Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O && createDefaultNotificationChannel)
            {
                // Create channel to show notifications.
                string channelId = DefaultNotificationChannelId;
                string channelName = DefaultNotificationChannelName;
                NotificationManager notificationManager = (NotificationManager)context.GetSystemService(Context.NotificationService);

                notificationManager.CreateNotificationChannel(new NotificationChannel(channelId,
                    channelName, NotificationImportance.Default));
            }


            System.Diagnostics.Debug.WriteLine(CrossAzurePushNotification.Current.Token);
        }

19 Source : AzurePushNotificationManager.android.cs
with MIT License
from CrossGeeks

public void Reset()
        {
            try
            {
                ThreadPool.QueueUserWorkItem(state =>
                {
                    CleanUp();
                });
            }
            catch (Exception ex)
            {
                _onNotificationError?.Invoke(CrossAzurePushNotification.Current, new AzurePushNotificationErrorEventArgs(AzurePushNotificationErrorType.UnregistrationFailed,ex.ToString()));
            }


        }

19 Source : PushNotificationManager.android.cs
with MIT License
from CrossGeeks

public void Reset()
        {
            try
            {
                ThreadPool.QueueUserWorkItem(state =>
                {
                    CleanUp();
                });
            }
            catch (Exception ex)
            {
                _onNotificationError?.Invoke(CrossPushNotification.Current, new PushNotificationErrorEventArgs(PushNotificationErrorType.UnregistrationFailed, ex.ToString()));
            }
        }

19 Source : FirebasePushNotificationManager.android.cs
with MIT License
from CrossGeeks

public static void Initialize(Context context, bool resetToken, bool createDefaultNotificationChannel = true, bool autoRegistration = true)
        {
            CrossFirebasePushNotification.Current.NotificationHandler = CrossFirebasePushNotification.Current.NotificationHandler ?? new DefaultPushNotificationHandler();
            FirebaseMessaging.Instance.AutoInitEnabled = autoRegistration;
            if (autoRegistration)
            {
                ThreadPool.QueueUserWorkItem(state =>
                {

                    var packageName = Application.Context.PackageManager.GetPackageInfo(Application.Context.PackageName, PackageInfoFlags.MetaData).PackageName;
                    var versionCode = Application.Context.PackageManager.GetPackageInfo(Application.Context.PackageName, PackageInfoFlags.MetaData).VersionCode;
                    var versionName = Application.Context.PackageManager.GetPackageInfo(Application.Context.PackageName, PackageInfoFlags.MetaData).VersionName;
                    var prefs = Android.App.Application.Context.GetSharedPreferences(FirebasePushNotificationManager.KeyGroupName, FileCreationMode.Private);

                    try
                    {

                        var storedVersionName = prefs.GetString(FirebasePushNotificationManager.AppVersionNameKey, string.Empty);
                        var storedVersionCode = prefs.GetString(FirebasePushNotificationManager.AppVersionCodeKey, string.Empty);
                        var storedPackageName = prefs.GetString(FirebasePushNotificationManager.AppVersionPackageNameKey, string.Empty);


                        if (resetToken || (!string.IsNullOrEmpty(storedPackageName) && (!storedPackageName.Equals(packageName, StringComparison.CurrentCultureIgnoreCase) || !storedVersionName.Equals(versionName, StringComparison.CurrentCultureIgnoreCase) || !storedVersionCode.Equals($"{versionCode}", StringComparison.CurrentCultureIgnoreCase))))
                        {
                            CleanUp(false);

                        }

                    }
                    catch (Exception ex)
                    {
                        _onNotificationError?.Invoke(CrossFirebasePushNotification.Current, new FirebasePushNotificationErrorEventArgs(FirebasePushNotificationErrorType.UnregistrationFailed, ex.ToString()));
                    }
                    finally
                    {
                        var editor = prefs.Edit();
                        editor.PutString(FirebasePushNotificationManager.AppVersionNameKey, $"{versionName}");
                        editor.PutString(FirebasePushNotificationManager.AppVersionCodeKey, $"{versionCode}");
                        editor.PutString(FirebasePushNotificationManager.AppVersionPackageNameKey, $"{packageName}");
                        editor.Commit();
                    }


                    CrossFirebasePushNotification.Current.RegisterForPushNotifications();


                });
            }


            if (Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O && createDefaultNotificationChannel)
            {
                // Create channel to show notifications.
                var channelId = DefaultNotificationChannelId;
                var channelName = DefaultNotificationChannelName;
                var notificationManager = (NotificationManager)context.GetSystemService(Context.NotificationService);

                Android.Net.Uri defaultSoundUri = SoundUri != null ? SoundUri : RingtoneManager.GetDefaultUri(RingtoneType.Notification);
                AudioAttributes attributes = new AudioAttributes.Builder()
                    .SetUsage(AudioUsageKind.Notification)
                    .SetContentType(AudioContentType.Sonification)
                    .SetLegacyStreamType(Stream.Notification)
                    .Build();

                NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, DefaultNotificationChannelImportance);
                notificationChannel.EnableLights(true);
                notificationChannel.SetSound(defaultSoundUri, attributes);

                notificationManager.CreateNotificationChannel(notificationChannel);
            }

            System.Diagnostics.Debug.WriteLine(CrossFirebasePushNotification.Current.Token);
        }

19 Source : FirebasePushNotificationManager.android.cs
with MIT License
from CrossGeeks

public static void Reset()
        {
            try
            {
                ThreadPool.QueueUserWorkItem(state =>
                {
                    CleanUp();
                });
            }
            catch (Exception ex)
            {
                _onNotificationError?.Invoke(CrossFirebasePushNotification.Current, new FirebasePushNotificationErrorEventArgs(FirebasePushNotificationErrorType.UnregistrationFailed, ex.ToString()));
            }


        }

19 Source : PushNotificationManager.android.cs
with MIT License
from CrossGeeks

public static void Initialize(Context context, bool resetToken, bool createNotificationChannel = true, bool autoRegistration = true)
        {
            _context = context;

            CrossPushNotification.Current.NotificationHandler = CrossPushNotification.Current.NotificationHandler ?? new DefaultPushNotificationHandler();
            FirebaseMessaging.Instance.AutoInitEnabled = autoRegistration;
            if (autoRegistration)
            {
                ThreadPool.QueueUserWorkItem(state =>
                {
                    var packageName = Application.Context.PackageManager.GetPackageInfo(Application.Context.PackageName, PackageInfoFlags.MetaData).PackageName;
                    var versionCode = Application.Context.PackageManager.GetPackageInfo(Application.Context.PackageName, PackageInfoFlags.MetaData).VersionCode;
                    var versionName = Application.Context.PackageManager.GetPackageInfo(Application.Context.PackageName, PackageInfoFlags.MetaData).VersionName;
                    var prefs = Application.Context.GetSharedPreferences(KeyGroupName, FileCreationMode.Private);

                    try
                    {
                        var storedVersionName = prefs.GetString(AppVersionNameKey, string.Empty);
                        var storedVersionCode = prefs.GetString(AppVersionCodeKey, string.Empty);
                        var storedPackageName = prefs.GetString(AppVersionPackageNameKey, string.Empty);

                        if (resetToken || (!string.IsNullOrEmpty(storedPackageName) && (!storedPackageName.Equals(packageName, StringComparison.CurrentCultureIgnoreCase) || !storedVersionName.Equals(versionName, StringComparison.CurrentCultureIgnoreCase) || !storedVersionCode.Equals($"{versionCode}", StringComparison.CurrentCultureIgnoreCase))))
                        {
                            ((PushNotificationManager)CrossPushNotification.Current).CleanUp();
                        }
                    }
                    catch (Exception ex)
                    {
                        _onNotificationError?.Invoke(CrossPushNotification.Current, new PushNotificationErrorEventArgs(PushNotificationErrorType.UnregistrationFailed, ex.ToString()));
                    }
                    finally
                    {
                        var editor = prefs.Edit();
                        editor.PutString(AppVersionNameKey, $"{versionName}");
                        editor.PutString(AppVersionCodeKey, $"{versionCode}");
                        editor.PutString(AppVersionPackageNameKey, $"{packageName}");
                        editor.Commit();
                    }
                    CrossPushNotification.Current.RegisterForPushNotifications();
                });
            }

            if (Build.VERSION.SdkInt >= BuildVersionCodes.O && createNotificationChannel)
            {
                if (NotificationChannels == null || NotificationChannels.Count() == 0)
                {
                    NotificationChannels = new List<NotificationChannelProps>()
                    {
                        new NotificationChannelProps(DefaultNotificationChannelId,
                                         DefaultNotificationChannelName,
                                         DefaultNotificationChannelImportance)
                    };
                }

                foreach (NotificationChannelProps channel in NotificationChannels)
                {
                    // Create channel to show notifications.
                    var channelId = channel.NotificationChannelId;
                    var channelName = channel.NotificationChannelName;
                    var channelImportance = channel.NotificationChannelImportance;
                    var notificationManager = (NotificationManager)context.GetSystemService(Context.NotificationService);
                    var notChannel = new NotificationChannel(channelId, channelName, channelImportance);

                    if (SoundUri != null)
                    {
                        try
                        {
                            var soundAttributes = new AudioAttributes.Builder()
                                                 .SetContentType(AudioContentType.Sonification)
                                                 .SetUsage(AudioUsageKind.Notification).Build();

                            notChannel.SetSound(SoundUri, soundAttributes);

                        }
                        catch (Exception ex)
                        {
                            System.Diagnostics.Debug.WriteLine(ex);
                        }

                    }

                    notificationManager.CreateNotificationChannel(notChannel);
                }
            }
            System.Diagnostics.Debug.WriteLine(CrossPushNotification.Current.Token);
        }

19 Source : HostForm.cs
with GNU General Public License v3.0
from CuteLeon

private void LoadRemoteURL()
        {
            this.WebBrowser.Load("https://StartUpPage.HackSystem.com");
            ThreadPool.QueueUserWorkItem(new WaitCallback((x) =>
            {
                Thread.Sleep(666);
                this.WebBrowser.Load($"{HostConfigs.RemoteURL}/{HostConfigs.StartURI}");
            }));
        }

19 Source : ExeProcess.cs
with MIT License
from cxwl3sxl

public void Start()
        {
            StartProcess();
            ThreadPool.QueueUserWorkItem(ProcessEye);
            _log.Info("服务已经成功启动.");
        }

19 Source : ReadWriteBufferTests.cs
with MIT License
from CyAScott

[Test]
        public async Task StressTest()
        {
            var randomData = new byte[1_048_576];//1 MB
            var readData = new byte[randomData.Length];
            var rnd = new Random(846845445);

            rnd.NextBytes(randomData);

            foreach (var __ in Enumerable.Range(0, 100))
            {
                using (var buffer = new ReadWriteBuffer(0))
                {
                    var readTask = new TaskCompletionSource<object>();
                    var timer = new Stopwatch();
                    var writeTask = new TaskCompletionSource<object>();

                    //write thread
                    ThreadPool.QueueUserWorkItem(async _ =>
                    {
                        try
                        {
                            var writeIndex = 0;

                            timer.Start();

                            while (writeIndex < randomData.Length)
                            {
                                var writeLength = Math.Min(rnd.Next(1, 1000), randomData.Length - writeIndex);
                                await buffer.Fill(new MemoryStream(randomData, writeIndex, writeLength, false), writeLength, CancellationToken.None).ConfigureAwait(false);
                                Thread.SpinWait(rnd.Next(1, 1000));
                                writeIndex += writeLength;
                            }

                            writeTask.TrySetResult(null);
                        }
                        catch (Exception error)
                        {
                            writeTask.TrySetException(error);
                        }
                    });

                    //read thread
                    ThreadPool.QueueUserWorkItem(async _ =>
                    {
                        try
                        {
                            var readIndex = 0;
                            while (readIndex < randomData.Length)
                            {
                                var readLength = await buffer.ReadAsync(readData, readIndex, Math.Min(rnd.Next(1, 1000), readData.Length - readIndex)).ConfigureAwait(false);
                                Thread.SpinWait(rnd.Next(1, 1000));
                                readIndex += readLength;
                            }

                            timer.Stop();

                            readTask.TrySetResult(null);
                        }
                        catch (Exception error)
                        {
                            readTask.TrySetException(error);
                        }
                    });

                    await Task.WhenAll(readTask.Task, writeTask.Task).ConfigureAwait(false);

                    Console.WriteLine($"Time: {timer.Elapsed.TotalMilliseconds:0.00} ms");

                    using (var md5 = MD5.Create())
                    {
                        var randomDataHash = new Guid(md5.ComputeHash(randomData));
                        var readDataHash = new Guid(md5.ComputeHash(readData));

                        Console.WriteLine($"random data ({randomDataHash}) == read data ({readDataHash})");

                        replacedert.AreEqual(randomDataHash, readDataHash);
                    }
                }
            }
        }

19 Source : MainForm.cs
with MIT License
from cyotek

private void RequestCurrentUser()
    {
      if (this.CanMakeRequests())
      {
        ThreadPool.QueueUserWorkItem(state =>
                                     {
                                       this.ExecuteRequest(() =>
                                                           {
                                                             _currentUser = _client.GetCurrentUser();

                                                             this.UpdateUserDisplay();
                                                           });
                                     });
      }
      else
      {
        _currentUser = new User();
        this.UpdateUserDisplay();
      }
    }

19 Source : MainForm.cs
with MIT License
from cyotek

private void RequestLoadIssues()
    {
      if (_selectedProject != null && !_issuesByProject.ContainsKey(_selectedProject.Id) && this.CanMakeRequests())
      {
        ThreadPool.QueueUserWorkItem(state =>
                                     {
                                       this.ExecuteRequest(() =>
                                                           {
                                                             int projectId;
                                                             Issue[] issues;

                                                             projectId = (int)state;

                                                             issues = _client.GetIssues(projectId).ToArray();

                                                             _issuesByProject[projectId] = issues;

                                                             this.UpdateIssuesList();
                                                           });
                                     }, _selectedProject.Id);
      }
      else
      {
        this.UpdateIssuesList();
      }
    }

19 Source : MainForm.cs
with MIT License
from cyotek

private void RequestLoadProjects()
    {
      _issuesByProject = new Dictionary<int, Issue[]>();

      if (this.CanMakeRequests())
      {
        ThreadPool.QueueUserWorkItem(state =>
                                     {
                                       this.ExecuteRequest(() =>
                                                           {
                                                             _projects = _client.GetProjects().ToArray();

                                                             this.UpdateProjectsList();
                                                           });
                                     });
      }
      else
      {
        _projects = new Project[0];
        this.UpdateProjectsList();
      }
    }

19 Source : RemoteSceneAccessServer.cs
with MIT License
from Daimler

public void Start()
        {
            ThreadPool.QueueUserWorkItem(delegate
            {
                this.controller.Start();
            });
        }

19 Source : RemoteSceneManipulationServer.cs
with MIT License
from Daimler

public void Start()
        {

            ThreadPool.QueueUserWorkItem(delegate
            {
                this.controller.Start();
            });
        }

19 Source : MMUAccess.cs
with MIT License
from Daimler

internal bool Connect(List<Tuple<string,int>> connections, TimeSpan timeout, string AvatarID)
        {
            //Fetch all modules and start them
            foreach (Tuple<string, int> connection in connections)
            {
                //Skip if adapter is already available
                if (this.Adapters.Exists(s => s.Description.Addresses[0].Address == connection.Item1 && s.Description.Addresses[0].Port == connection.Item2))
                    continue;

                RemoteAdapterAccess module = new RemoteAdapterAccess(connection.Item1, connection.Item2, new MAdapterDescription("Manual connection", Guid.NewGuid().ToString(), "Remote", new List<MIPAddress>() { new MIPAddress(connection.Item1, connection.Item2) }), this);

                this.Adapters.Add(module);
            }


            Stopwatch watch = new Stopwatch();
            watch.Start();
            bool finished = false;

            ThreadPool.QueueUserWorkItem(delegate
            {
                //Start all modules
                foreach (IAdapter accessingModule in this.Adapters)
                {
                    //To do investigate mutlithreading support
                    //Start the module
                    accessingModule.Start();

                    //Create the session
                    accessingModule.CreateSession(this.SessionId, this.SkeletonAccess.GetAvatarDescription(AvatarID));
                }

                finished = true;
            });

            //Wait until timeout or finished
            while (!finished && watch.Elapsed < timeout)
            {
                Thread.Sleep(10);
            }

            return finished;
        }

19 Source : AdapterController.cs
with MIT License
from Daimler

public virtual void Start()
        {
            Logger.Log(Log_level.L_INFO, $"Starting adapter server at {address.Address} {address.Port}: ");

            //Set the start time
            this.SessionData.StartTime = DateTime.Now;

            //Create and start the registration handler
            this.registrationHandler = new AdapterRegistrationHandler(this.mmiRegisterAddress, this.adapterDescription);
           
            //Scan the loadable MMUs
            SessionData.MMULoadingProperties = this.mmuProvider.GetAvailableMMUs();
            this.UpdateAvailableMMUDescriptions(SessionData.MMULoadingProperties);

            //Create and start the thrift server
            this.thriftServer = new AdapterServer(this.address.Address, this.address.Port, this.adapterImplementation);

            //Start the adapter controller in separate thread
            ThreadPool.QueueUserWorkItem(delegate
            {
                this.thriftServer.Start();
                this.Started = true;
            });
        }

19 Source : ServiceController.cs
with MIT License
from Daimler

public virtual void Start()
        {

            //Create and start the registration handler
            this.registrationHandler = new ServiceRegistrationHandler(this.mmiRegisterAddress, this.serviceDescription);

            //Create and start the thrift server
            this.thriftServer = new ThriftServerBase(this.address.Address, this.address.Port, this.processor);

            //Start the adapter controller in separate thread
            ThreadPool.QueueUserWorkItem(delegate
            {
                this.thriftServer.Start();
                this.Started = true;
            });
        }

19 Source : MMIRegisterThriftServer.cs
with MIT License
from Daimler

public void Start()
        {
            MMIRegisterService.Processor processor = new MMIRegisterService.Processor(implementation);

            TServerTransport serverTransport = new TServerSocket(this.port);

            //Use a mulreplacedhreaded server
            this.server = new TThreadPoolServer(processor, serverTransport, new BufferedTransportFactory(), new TCompactProtocol.Factory());

            Console.WriteLine($"Starting the server at {this.port}");

            //Start the server in a new thread
            ThreadPool.QueueUserWorkItem(delegate
            {
                this.server.Serve();
            });
        }

19 Source : RemoteAdapter.cs
with MIT License
from Daimler

public void Start()
        {
            //Cyclicyll update the status
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                while (!this.Aborted)
                {
                    System.Threading.Thread.Sleep(this.UpdateTime);

                    try
                    {
                        //Get the status 
                        this.Status = this.GetStatus().GetReadableString();

                        this.Initialized = true;

                        this.InactiveTime = TimeSpan.Zero;
                        this.Active = true;
                    }
                    catch (Exception)
                    {

                        this.InactiveTime += UpdateTime;
                        this.Active = false;
                        this.Status = "Inactive: " + this.InactiveTime.Duration().ToString();

                        if (this.InactiveTime > RuntimeData.InactiveRemoveTime)
                        {
                            RemoteAdapter removed = null;
                            RuntimeData.AdapterInstances.TryRemove(this.Description.ID, out removed);

                            //Fire event if it gets inactiv
                            this.OnInactive?.Invoke(this, this);

                            //UIData.SynchronizeAdapters();
                        }
                    }

                }
            });
        }

19 Source : RemoteService.cs
with MIT License
from Daimler

public void Start()
        {
            //Cyclicyll update the status
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                while (!this.Aborted)
                {
                    System.Threading.Thread.Sleep(this.UpdateTime);

                    try
                    {
                        this.Status = this.GetStatus().GetReadableString();

                        this.Initialized = true;
                        this.InactiveTime = TimeSpan.Zero;
                        this.Active = true;
                    }
                    catch //(Exception e)
                    {
                        this.InactiveTime += this.UpdateTime;
                        this.Active = false;
                        this.Status = "Inactive: " + this.InactiveTime.Duration().ToString();

                        if (this.InactiveTime > RuntimeData.InactiveRemoveTime)
                        {
                            RemoteService removed = null;
                            RuntimeData.ServiceInstances.TryRemove(this.Description.ID, out removed);

                            //Fire event if it gets inactiv
                            this.OnInactive?.Invoke(this, this);
                        }

                    }
                }
            });

        }

19 Source : CommonTestsBase.cs
with MIT License
from DaniilSokolyuk

[Fact]
		public virtual void ScriptInterruptionIsCorrect()
		{
			// Arrange
			const string sleepyСode = @"function sleep(millisecondsTimeout) {
	var totalMilliseconds = new Date().getTime() + millisecondsTimeout;

	while (new Date() < totalMilliseconds)
	{ }
}

waitHandle.Set();
sleep(5000);";

			const string input = "!0";
			const bool targetOutput = true;

			// Act
			bool supportsScriptInterruption;
			Exception currentException = null;
			bool output;

			using (var jsEngine = CreateJsEngine())
			{
				supportsScriptInterruption = jsEngine.SupportsScriptInterruption;
				if (supportsScriptInterruption)
				{
					using (var waitHandle = new ManualResetEvent(false))
					{
						ThreadPool.QueueUserWorkItem(state =>
						{
							waitHandle.WaitOne();
							jsEngine.Interrupt();
						});

						jsEngine.EmbedHostObject("waitHandle", waitHandle);

						try
						{
							jsEngine.Execute(sleepyСode);
						}
						catch (Exception e)
						{
							currentException = e;
						}
					}
				}

				output = jsEngine.Evaluate<bool>(input);
			}

			// replacedert
			if (supportsScriptInterruption)
			{
				replacedert.IsType<JsInterruptedException>(currentException);
			}
			replacedert.Equal(targetOutput, output);
		}

See More Examples