コード例 #1
0
ファイル: frmMain.cs プロジェクト: oduslabs/4chan-Scraper
        private async void btnStart_Click(object sender, EventArgs e)
        {
            pbMain.Value = 0;
            ToggleGroupBoxes(false);

            TitleBuilder.Build(this, "Initializing");

            try
            {
                var threadInfo = new ThreadInfo(txtThread.Text);

                var scraper = new Scraper(threadInfo, UpdateProgress);
                var files = await scraper.CollectFilePosts(cbWEBM.Checked, cbDuplicates.Checked);

                pbMain.Maximum = files.Count;

                await Task.WhenAll(files.Select(p =>
                    scraper.DownloadAsync(p, rbUID.Checked, txtPath.Text, this)));

                TitleBuilder.Build(this, "Completed", false);
            }
            catch (Exception ex)
            {
                TitleBuilder.Build(this, ex.Message, false);
            }

            ToggleGroupBoxes(true);
        }
コード例 #2
0
ファイル: ThreadsPad.cs プロジェクト: zcf7822/monodevelop
        void UpdateThread(TreeIter iter, ThreadInfo thread, ThreadInfo activeThread)
        {
            var weight = thread == activeThread ? Pango.Weight.Bold : Pango.Weight.Normal;
            var icon   = thread == activeThread ? Gtk.Stock.GoForward : null;

            store.SetValue(iter, (int)Columns.Weight, (int)weight);
            store.SetValue(iter, (int)Columns.Icon, icon);
        }
コード例 #3
0
 protected override void OnStarted(ThreadInfo t)
 {
     base.OnStarted(t);
     if (simProcess != null)
     {
         IPhoneUtility.MakeSimulatorGrabFocus();
     }
 }
コード例 #4
0
ファイル: ThreadPond.cs プロジェクト: surfsky/App.Utils
        //--------------------------------------------
        // 线程处理主体
        void StartThread(object o)
        {
            ThreadInfo info = o as ThreadInfo;

            SetThreadStatus(info, true);
            info.Action(info.Parameter);
            SetThreadStatus(info, false);
        }
コード例 #5
0
        /// <summary>
        /// Get thread info from the provided page.
        /// </summary>
        /// <param name="page">A web page from a forum that this adapter can handle.</param>
        /// <returns>Returns thread information that can be gleaned from that page.</returns>
        public ThreadInfo GetThreadInfo(HtmlDocument page)
        {
            if (page == null)
            {
                throw new ArgumentNullException(nameof(page));
            }

            string title;
            string author;
            int    pages;

            HtmlNode doc = page.DocumentNode;

            // Find the page title
            title = PostText.CleanupWebString(doc.Element("html").Element("head")?.Element("title")?.InnerText);

            // Find a common parent for other data
            HtmlNode pageContent = GetPageContent(page, PageType.Thread);

            if (pageContent == null)
            {
                throw new InvalidOperationException("Cannot find content on page.");
            }

            // Find the thread author
            HtmlNode titleBar = pageContent.GetDescendantWithClass("titleBar");

            // Non-thread pages (such as threadmark pages) won't have a title bar.
            if (titleBar == null)
            {
                throw new InvalidOperationException("Not a valid forum thread.");
            }

            var pageDesc = page.GetElementbyId("pageDescription");

            var authorNode = pageDesc?.GetChildWithClass("username");

            author = PostText.CleanupWebString(authorNode?.InnerText);

            // Find the number of pages in the thread
            var    pageNavLinkGroup = pageContent.GetDescendantWithClass("div", "pageNavLinkGroup");
            var    pageNav          = pageNavLinkGroup?.GetChildWithClass("PageNav");
            string lastPage         = pageNav?.GetAttributeValue("data-last", "");

            if (string.IsNullOrEmpty(lastPage))
            {
                pages = 1;
            }
            else
            {
                pages = Int32.Parse(lastPage);
            }

            // Create a ThreadInfo object to hold the acquired information.
            ThreadInfo info = new ThreadInfo(title, author, pages);

            return(info);
        }
コード例 #6
0
        static void Main(string[] args)
        {
            var entryThreadInfo = ThreadInfo.GetCurrentThreadInfo();

            // shows how to block the execution when it's not possible to mark containing method as async
            string result = dotNet45Task.ASyncCallWithContinuation().GetAwaiter().GetResult();

            var returningThreadInfo = ThreadInfo.GetCurrentThreadInfo();
        }
コード例 #7
0
        internal override void ProcessData(AmcpParsedData data)
        {
            base.ProcessData(data);

            for (var i = 1; i < data.Data.Count; i++)
            {
                _threadList.Add(ThreadInfo.Parse(data.Data[i]));
            }
        }
コード例 #8
0
            public static ThreadInfo GetThreadInfo(ThreadQueueAttribute threadQueue)
            {
                ThreadInfo info = new ThreadInfo();

                info.Type       = threadQueue.Type.ToString();
                info.Count      = threadQueue.Count;
                info.UniqueName = threadQueue.UniqueName;
                return(info);
            }
コード例 #9
0
ファイル: phpBBAdapter.cs プロジェクト: MizMahem/NetTally
        /// <summary>
        /// Get thread info from the provided page.
        /// </summary>
        /// <param name="page">A web page from a forum that this adapter can handle.</param>
        /// <returns>Returns thread information that can be gleaned from that page.</returns>
        public ThreadInfo GetThreadInfo(HtmlDocument page)
        {
            if (page == null)
            {
                throw new ArgumentNullException(nameof(page));
            }

            string title;
            string author = string.Empty;
            int    pages  = 1;

            HtmlNode doc = page.DocumentNode.Element("html");

            // Find the page title
            title = ForumPostTextConverter.CleanupWebString(doc.Element("head")?.Element("title")?.InnerText);

            // Find the number of pages
            var pagebody = page.GetElementbyId("page-body");

            if (pagebody != null)
            {
                // Different versions of the forum have different methods of showing page numbers

                var topicactions = pagebody.GetChildWithClass("topic-actions");
                if (topicactions != null)
                {
                    HtmlNode?pagination     = topicactions.GetChildWithClass("pagination");
                    string?  paginationText = pagination?.InnerText;
                    if (paginationText != null)
                    {
                        Regex pageOf = new Regex(@"Page\s*\d+\s*of\s*(?<pages>\d+)");
                        Match m      = pageOf.Match(paginationText);
                        if (m.Success)
                        {
                            pages = int.Parse(m.Groups["pages"].Value);
                        }
                    }
                }
                else
                {
                    var actionbar  = pagebody.GetChildWithClass("action-bar");
                    var pagination = actionbar?.GetChildWithClass("pagination");

                    var ul           = pagination?.Element("ul");
                    var lastPageLink = ul?.Elements("li")?.LastOrDefault(n => !n.GetAttributeValue("class", "").Split(' ').Contains("next"));

                    if (lastPageLink != null)
                    {
                        pages = int.Parse(lastPageLink.InnerText);
                    }
                }
            }

            ThreadInfo info = new ThreadInfo(title, author, pages);

            return(info);
        }
コード例 #10
0
ファイル: MonoThreadManager.cs プロジェクト: vasek-cz/vs-mono
 public MonoThread this[ThreadInfo thread]
 {
     get
     {
         var result = threads[thread.Id];
         result.SetDebuggedThread(thread);
         return(result);
     }
 }
コード例 #11
0
        private static ThreadInfo GetThreadInfo(ClrThread thread, DataTarget dataTarget,
                                                ClrRuntime runtime, StringBuilder sb, bool includeStackObjects)
        {
            var hasStackTrace = thread.StackTrace.Count > 0;

            var threadInfo = new ThreadInfo
            {
                OSThreadId      = thread.OSThreadId,
                ManagedThreadId = thread.ManagedThreadId,
                IsNative        = hasStackTrace == false,
                ThreadType      = thread.IsGC ? ThreadType.GC :
                                  thread.IsFinalizer ? ThreadType.Finalizer :
                                  hasStackTrace == false ? ThreadType.Native : ThreadType.Other
            };

            if (hasStackTrace)
            {
                foreach (var frame in thread.StackTrace)
                {
                    if (frame.DisplayString.Equals("GCFrame", StringComparison.OrdinalIgnoreCase) ||
                        frame.DisplayString.Equals("DebuggerU2MCatchHandlerFrame", StringComparison.OrdinalIgnoreCase))
                    {
                        continue;
                    }

                    threadInfo.StackTrace.Add(frame.DisplayString);
                }
            }
            else if (dataTarget.DebuggerInterface != null)
            {
                var control      = (IDebugControl)dataTarget.DebuggerInterface;
                var sysObjs      = (IDebugSystemObjects)dataTarget.DebuggerInterface;
                var nativeFrames = new DEBUG_STACK_FRAME[100];
                var sybSymbols   = (IDebugSymbols)dataTarget.DebuggerInterface;

                threadInfo.IsNative = true;

                sysObjs.SetCurrentThreadId(threadInfo.OSThreadId);

                control.GetStackTrace(0, 0, 0, nativeFrames, 100, out var frameCount);

                for (var i = 0; i < frameCount; i++)
                {
                    sb.Clear();
                    sybSymbols.GetNameByOffset(nativeFrames[i].InstructionOffset, sb, sb.Capacity, out _, out _);

                    threadInfo.StackTrace.Add(sb.ToString());
                }
            }

            if (includeStackObjects)
            {
                threadInfo.StackObjects = GetStackObjects(runtime, thread);
            }

            return(threadInfo);
        }
コード例 #12
0
        /// <summary>
        /// Определяет, содержится ли указанный экземпляр в списке отображения.
        /// </summary>
        /// <param name="info">Проверяемый экземпляр.</param>
        /// <returns>Истина - содержится, иначе - ложь.</returns>
        public bool Contains(ThreadInfo info)
        {
            if (info == null)
                throw new ArgumentNullException("Проверяемая информация не может быть неопределенной");

            int i = listView.Items.OfType<ListViewItem>().ToList().FindIndex(x => (x.Tag as ThreadInfo) == info);

            return i >= 0;
        }
コード例 #13
0
 protected void Push(string region_name, string file, uint line)
 {
     if (IsRecording())
     {
         ThreadInfo threadInfo = ManifestThreadInfo(null);
         threadInfo.regionStack.Push(region_name);
         threadInfo.WriteLine(category, region_name, sw, "B", "},");
     }
 }
コード例 #14
0
        /// <summary>
        /// Enter watch dog
        /// </summary>
        /// <param name="timeout">in millisecond</param>
        internal void Enter(int timeout, string tableName)
        {
            if (timeout <= 0)
            {
                return;
            }

            if (System.Threading.Monitor.TryEnter(_LockObj, 200))
            {
                try
                {
                    if (_Thread == null)
                    {
                        _Thread = new Thread(ThreadProc);
                        _Thread.IsBackground = true;
                        _Thread.Start();
                    }

                    Thread thread = Thread.CurrentThread;

                    ThreadInfo threadInfo;
                    if (_ThreadIdToThread.TryGetValue(thread.ManagedThreadId, out threadInfo))
                    {
                        threadInfo.TimeRemain = timeout;
                    }
                    else
                    {
                        if (CurrentConnection.ConnectionInfo != null)
                        {
                            if (CurrentConnection.ConnectionInfo.QueryThread != null)
                            {
                                threadInfo = new ThreadInfo(tableName, timeout,
                                                            CurrentConnection.ConnectionInfo.QueryThread);
                            }
                            else
                            {
                                threadInfo = new ThreadInfo(tableName, timeout, thread);
                            }
                        }
                        else
                        {
                            threadInfo = new ThreadInfo(tableName, timeout, thread);
                        }

                        _ThreadIdToThread.Add(thread.ManagedThreadId, threadInfo);
                    }
                }
                catch (Exception e)
                {
                    Global.Report.WriteErrorLog("Select Watch dog Enter.", e);
                }
                finally
                {
                    System.Threading.Monitor.Exit(_LockObj);
                }
            }
        }
コード例 #15
0
 public ThreadPreviewInfoResult(ThreadInfo threadInfo)
 {
     Id                  = threadInfo.Id;
     Title               = threadInfo.Title;
     AuthorUsername      = threadInfo.AuthorUsername;
     SectionName         = threadInfo.SectionName;
     CreationDateTimeUtc = threadInfo.CreationDateTimeUtc;
     LikesDislikes       = threadInfo.LikesDislikes;
 }
コード例 #16
0
        public static string StringizeThread(ThreadInfo thread, bool includeFrame)
        {
            var f = includeFrame ? thread.Backtrace.GetFrame(0) : null;

            var fstr = f == null ? string.Empty : Environment.NewLine + StringizeFrame(f, false);
            var tstr = string.Format("Thread #{0} '{1}'", thread.Id, thread.Name);

            return(string.Format("{0}{1}", tstr, fstr));
        }
コード例 #17
0
            public static ThreadInfo Impersonate(ThreadInfo ti)
            {
                ExceptionHelper.ThrowIfArgumentNull(ti, "ti");

                ThreadInfo prevInfo = Capture(true, true);

                Restore(ti);
                return(prevInfo);
            }
コード例 #18
0
        internal static string BuildMessageInternal(IEvent @event, IThreadCollection threads)
        {
            ThreadInfo threadInfo = threads[@event.Unit];

            if (threadInfo == null)
            {
                return("<UNKNOWN THREAD DESTROYED>");
            }
            return(string.Format("Thread {0} destroyed", threadInfo.Id));
        }
コード例 #19
0
        public string FormatName(IEvent @event)
        {
            ThreadInfo threadInfo = _threads.FirstOrDefault(x => x.OsThreadId == @event.ThreadUid);

            if (threadInfo == null)
            {
                return("<UNKNOWN FUNCTION>");
            }
            return(string.Format("{0} #{1}", threadInfo.Name, threadInfo.Uid));
        }
コード例 #20
0
ファイル: ThreadPond.cs プロジェクト: surfsky/App.Utils
        // 设置线程状态
        void SetThreadStatus(ThreadInfo info, bool running)
        {
            var txt = string.Format("线程 {0} {1}", info.ThreadId, info.Running ? "开启" : "关闭");

            Log.Invoke(txt);
            lock (info)
            {
                info.Running = running;
            }
        }
コード例 #21
0
        private void ThreadEntry(object state)
        {
            ThreadInfo info = (ThreadInfo)state;

            using (NSAutoreleasePool pool = new NSAutoreleasePool())
            {
                DownloadAndSave(info.Item);
                info.WaitHandle.Set();
            }
        }
コード例 #22
0
 void Update()
 {
     lock (dataQueue) {
         while (dataQueue.Count > 0)
         {
             ThreadInfo threadInfo = dataQueue.Dequeue();
             threadInfo.callback(threadInfo.parameter);
         }
     }
 }
コード例 #23
0
        /////////////////////////////////////////////////////////////
        // Use: Returns Thread Pitch as string using default units.
        //
        /////////////////////////////////////////////////////////////
        public static string GetThreadPitchStr(ThreadInfo threadInfo,
                                               Document doc)
        {
            double pitch = ThreadWorker.GetThreadPitch(threadInfo);

            UnitsOfMeasure uom = doc.UnitsOfMeasure;

            return(uom.GetStringFromValue(pitch,
                                          UnitsTypeEnum.kDefaultDisplayLengthUnits));
        }
コード例 #24
0
    public static ThreadInfo RequestData(Func <object> generateData, Action <object> callback, QueueCategory queueCategory = QueueCategory.Default, QueuePriority queuePriority = QueuePriority.High)
    {
        ThreadInfo queueThreadInfo = new ThreadInfo();

        ThreadStart threadStart = delegate { queueThreadInfo = Instance.DataThread(generateData, callback, queueCategory, queuePriority); };

        new Thread(threadStart).Start();

        return(queueThreadInfo);
    }
コード例 #25
0
 void Update() {
     //both of these blocks effectively do the same thing, just one with HeightMap and the other with MeshData
     //if there's stuff in the Queue, take it out and execute the callback
     if (dataQueue.Count > 0) {
         for (int i = 0; i < dataQueue.Count; i++) {
             ThreadInfo threadInfo = dataQueue.Dequeue();
             threadInfo.callback(threadInfo.parameter);
         }
     }
 }
コード例 #26
0
        private bool FilterByName(object item, string text)
        {
            if (string.IsNullOrWhiteSpace(text))
            {
                return(true);
            }
            ThreadInfo threadInfo = (ThreadInfo)item;

            return(threadInfo.Name.IndexOf(text, StringComparison.InvariantCultureIgnoreCase) >= 0);
        }
コード例 #27
0
        private void OnMicroThreadStateChanged(object sender, SchedulerEventArgs e)
        {
            if (e.MicroThreadPreviousState == MicroThreadState.None)
            {
                return;
            }

            if (frameInfo == null)
            {
                return;
            }

            double currentTime = stopwatch.Elapsed;

            int  threadId      = Thread.CurrentThread.ManagedThreadId;
            long microThreadId = e.MicroThread.Id;

            ThreadInfo threadInfo = frameInfo.ThreadItems.FirstOrDefault(ti => ti.Id == threadId);

            if (threadInfo == null)
            {
                threadInfo = new ThreadInfo {
                    Id = threadId
                };
                frameInfo.ThreadItems.Add(threadInfo);
            }

            // pending state is used to keep trace of the micro threads recently added as 'running'
            // in order to create a proper MicroThreadInfo item when then receiving a 'waiting' notification
            MicroThreadPendingState pendingState;

            if (pendingMicroThreads.TryGetValue(microThreadId, out pendingState))
            {
                threadInfo.MicroThreadItems.Add(new MicroThreadInfo
                {
                    Id         = microThreadId,
                    BeginState = pendingState.State,
                    EndState   = e.MicroThread.State,
                    BeginTime  = Math.Max(pendingState.Time, frameInfo.BeginTime),
                    EndTime    = currentTime,
                });

                pendingMicroThreads.Remove(microThreadId);
            }
            else if (e.MicroThread.IsOver == false)
            {
                pendingMicroThreads.Add(microThreadId, new MicroThreadPendingState
                {
                    ThreadId    = threadInfo.Id,
                    Time        = currentTime,
                    State       = e.MicroThread.State,
                    MicroThread = e.MicroThread,
                });
            }
        }
コード例 #28
0
        public void PacketCacheTest()
        {
            m_PacketReader.RegisterType(typeof(WrapperPacket));
            m_PacketReader.RegisterType(typeof(LogPacket));
            m_PacketReader.RegisterType(typeof(ThreadInfo));

            //since timestamp length varies by time zone we have to measure it first (sigh..)
            var  timestampLength = DateTimeOffsetSerializedLength();
            bool haveTimeZone    = timestampLength == 12;

            //The first message has to write out a bunch of stuff - definitions, threads, etc.
            LogPacket.Write("message 1", 101, m_PacketWriter);
            Assert.AreEqual(133 + timestampLength, m_MemoryStream.Position,
                            "Serialized value isn't the expected length.  Position is: {1}, expected {0}.\r\nSerialized Value: {2}",
                            m_MemoryStream.Position, 133 + timestampLength, m_MemoryStream.ToArray().ToDisplayString());

            Thread.Sleep(50);

            //having now written that these messages will be smaller because we don't have to write out threads and timestamps are smaller.
            var baseline = m_MemoryStream.Position;

            LogPacket.Write("message 2", 101, m_PacketWriter);
            Assert.AreEqual(haveTimeZone ? 20 : 19, m_MemoryStream.Position - baseline);
            Thread.Sleep(50);

            baseline = m_MemoryStream.Position;
            LogPacket.Write("message 3", 101, m_PacketWriter);
            Assert.AreEqual(haveTimeZone ? 20 : 19, m_MemoryStream.Position - baseline);

            baseline = m_MemoryStream.Position;
            LogPacket.Write("message 1", 101, m_PacketWriter);
            Assert.AreEqual(haveTimeZone ? 20 : 19, m_MemoryStream.Position - baseline);

            m_MemoryStream.Position = 0;

            ThreadInfo threadInfo = (ThreadInfo)m_PacketReader.Read();
            LogPacket  message1   = (LogPacket)m_PacketReader.Read();
            LogPacket  message2   = (LogPacket)m_PacketReader.Read();
            LogPacket  message3   = (LogPacket)m_PacketReader.Read();
            LogPacket  message4   = (LogPacket)m_PacketReader.Read();

            Assert.AreEqual(101, threadInfo.ThreadId);
            Assert.AreEqual(101, message1.ThreadId);
            Assert.AreEqual("message 1", message1.Caption);
            Assert.LessOrEqual(message1.TimeStamp, DateTime.Now);
            Assert.AreEqual(101, message2.ThreadId);
            Assert.AreEqual("message 2", message2.Caption);
            Assert.LessOrEqual(message1.TimeStamp, message2.TimeStamp);
            Assert.AreEqual(101, message3.ThreadId);
            Assert.AreEqual("message 3", message3.Caption);
            Assert.LessOrEqual(message2.TimeStamp, message3.TimeStamp);
            Assert.AreEqual("message 1", message4.Caption);
            Assert.LessOrEqual(message3.TimeStamp, message4.TimeStamp);
        }
コード例 #29
0
 void Update()
 {
     if (dataQueue.Count > 0)
     {
         for (int i = 0; i < dataQueue.Count; i++)
         {
             ThreadInfo threadInfo = dataQueue.Dequeue();
             threadInfo.callback(threadInfo.parameter);
         }
     }
 }
コード例 #30
0
        public void MustCorrectlyFormatLogMessage()
        {
            var sut        = new DefaultLogFormatter();
            var date       = new DateTime(2017, 10, 10, 15, 24, 38);
            var threadInfo = new ThreadInfo(1234, "ABC");
            var entry      = new LogMessage(date, LogLevel.Warning, "Here's a warning message...", threadInfo);

            var text = sut.Format(entry);

            Assert.AreEqual($"2017-10-10 15:24:38.000 [1234: ABC] - WARNING: Here's a warning message...", text);
        }
コード例 #31
0
 private void Update()
 {
     if (dataQueue.Count > 0)
     {
         for (int i = 0; i < dataQueue.Count; i++)
         {
             ThreadInfo threadInfo = dataQueue.Dequeue();
             threadInfo.callback(threadInfo.parameter);  // call the passed function with the appropriate parameter
         }
     }
 }
コード例 #32
0
        /// <summary>
        ///
        /// </summary>
        void ThreadExecute(object threadInfoParam)
        {
            ThreadInfo threadInfo = threadInfoParam as ThreadInfo;

            GeneralHelper.AssignThreadCulture();

            while (IsRunning)
            {
                TargetInfo targetInfo = null;
                if (_queue.Count != 0)
                {
                    lock (_queue)
                    {
                        if (_queue.Count > 0)
                        {
                            targetInfo = _queue.Dequeue();
                        }
                    }

                    Interlocked.Exchange(ref _lastQueueItemProcessedMillisecond, GeneralHelper.ApplicationStopwatchMilliseconds);
                }

                if (targetInfo == null)
                {
                    lock (_sleepingThreads)
                    {
                        // Keep this locked.
                        if (IsRunning == false)
                        {// Do not enter sleeping mode, if we are already stopped.
                            return;
                        }
                        _sleepingThreads.Push(threadInfo);
                    }

                    threadInfo.Event.WaitOne();

                    if (threadInfo.MustDispose)
                    {// Instructed to dispose.
                        return;
                    }
                }
                else
                {
                    try
                    {
                        object invokeResult = targetInfo.Invoke();
                    }
                    catch (Exception ex)
                    {
                        InstanceSystem.OperationError(SystemMonitor.ProcessExceptionMessage("[" + _name + "] Thread executed caused an exception ", ex));
                    }
                }
            }
        }
コード例 #33
0
        /// <summary>
        /// Добавляет информацию о потоке в список.
        /// </summary>
        /// <param name="info">Отображаемая базовая информация.</param>
        /// <param name="selected">Определяет, является ли добавляемая информация выделенной.</param>
        public void AddThreadInfo(ThreadInfo info, bool selected)
        {
            if (info == null)
                throw new ArgumentNullException("Отображаемая информация не может быть неопределенной");

            ListViewItem item = new ListViewItem();
            item.Text = info.Id.ToString();
            item.SubItems.Add(info.Program);
            item.SubItems.Add(info.Command.ToString());
            item.Tag = info;
            listView.Items.Add(item);
            item.Checked = selected;

            listView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
        }
コード例 #34
0
ファイル: Scraper.cs プロジェクト: oduslabs/4chan-Scraper
    /// <summary>
    /// Initializes the scraper.
    /// </summary>
    /// <param name="threadInfo">A <paramref name="ThreadInfo"/> model of the thread.</param>
    /// <param name="action">An action to invoke on completion.</param>
    public Scraper(ThreadInfo threadInfo, Action action)
    {
        var handler = new HttpClientHandler
        {
            AllowAutoRedirect = true,
            AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,

            UseCookies = false,
            UseProxy = false
        };

        _client = new HttpClient(handler);
        _thread = threadInfo;

        _updateAction = action;
    }
コード例 #35
0
        public GlacierizerUploader(GlacierAPIInterface api, Stream input, int partSize, short numThreads)
        {
            glacierAPI = api;
            inputStream = input;
            this.partSize = partSize;
            numRequestedThreads = numThreads;

            threads = new List<ThreadInfo>();
            for (int i = 0; i < numRequestedThreads; ++i)
            {
                ThreadInfo info = new ThreadInfo(partSize);
                threads.Add(info);
            }

            hashList = new List<string>();

            transferMetric = new TransferMetric();
        }
コード例 #36
0
ファイル: BroadCasterTest.cs プロジェクト: kilfour/QuickAcid
        private static QAcidRunner<Unit> Broadcast(Broadcaster broadcaster, ThreadInfo info)
        {
            return
                from canact in
                    "when threadswitch is false".If(
                        () => info.ThreadSwitch == false,
                        from start in "start broadcasting".Act(
                            () =>
                                {
                                    info.ThreadSwitch = true;
                                    info.ExceptionFromThread = null;
                                    info.Thread =
                                        new Thread(
                                            () => info.ExceptionFromThread =
                                                  GetExceptionThrownBy(
                                                  	() => broadcaster.Broadcast(null)));

                                    info.Thread.Start();
                                })
                        from spec in "Broadcast : No Exception is thrown".Spec(() => info.ExceptionFromThread == null)
                        select Unit.Instance)
                select Unit.Instance;
        }
コード例 #37
0
		internal protected void OnTargetEvent (TargetEventArgs args)
		{
			currentProcesses = null;
			
			if (args.Process != null)
				args.Process.Attach (this);
			if (args.Thread != null) {
				args.Thread.Attach (this);
				activeThread = args.Thread;
			}
			if (args.Backtrace != null)
				args.Backtrace.Attach (this);
			
			switch (args.Type) {
				case TargetEventType.ExceptionThrown:
					lock (slock) {
						isRunning = false;
						args.IsStopEvent = true;
					}
					if (TargetExceptionThrown != null)
						TargetExceptionThrown (this, args);
					break;
				case TargetEventType.TargetExited:
					lock (slock) {
						isRunning = false;
						started = false;
					}
					if (TargetExited != null)
						TargetExited (this, args);
					break;
				case TargetEventType.TargetHitBreakpoint:
					lock (slock) {
						isRunning = false;
						args.IsStopEvent = true;
					}
					if (TargetHitBreakpoint != null)
						TargetHitBreakpoint (this, args);
					break;
				case TargetEventType.TargetInterrupted:
					lock (slock) {
						isRunning = false;
						args.IsStopEvent = true;
					}
					if (TargetInterrupted != null)
						TargetInterrupted (this, args);
					break;
				case TargetEventType.TargetSignaled:
					lock (slock) {
						isRunning = false;
						args.IsStopEvent = true;
					}
					if (TargetSignaled != null)
						TargetSignaled (this, args);
					break;
				case TargetEventType.TargetStopped:
					lock (slock) {
						isRunning = false;
						args.IsStopEvent = true;
					}
					if (TargetStopped != null)
						TargetStopped (this, args);
					break;
				case TargetEventType.UnhandledException:
					lock (slock) {
						isRunning = false;
						args.IsStopEvent = true;
					}
					if (TargetUnhandledException != null)
						TargetUnhandledException (this, args);
					break;
				case TargetEventType.TargetReady:
					if (TargetReady != null)
						TargetReady (this, args);
					break;
				case TargetEventType.ThreadStarted:
					if (TargetThreadStarted != null)
						TargetThreadStarted (this, args);
					break;
				case TargetEventType.ThreadStopped:
					if (TargetThreadStopped != null)
						TargetThreadStopped (this, args);
					break;
			}
			if (TargetEvent != null)
				TargetEvent (this, args);
		}
コード例 #38
0
		public void NotifyStarted (ThreadInfo t)
		{
			session.OnStarted (t);
		}
コード例 #39
0
		internal protected virtual void OnStarted (ThreadInfo t)
		{
			OnTargetEvent (new TargetEventArgs (TargetEventType.TargetReady) { Thread = t });
			lock (slock) {
				started = true;
				foreach (BreakEvent bp in breakpointStore)
					AddBreakEvent (bp);
			}
		}
コード例 #40
0
ファイル: UserRemoteObject.cs プロジェクト: JVasques/User
        private void PrepareRetryTwoPhaseCommit(List<UserView> listToSend, ReservationMessage reservation)
        {
            Console.WriteLine("[Calling] PrepareRetryTwoPhaseCommit");
            List<UserInterface> usersProxy = new List<UserInterface>();

            lock (User.userLoger)
            {
                User.userLoger.IncrementNumberOfExchangedMessages("TwoPhaseCommit");
            }

            foreach (UserView u in listToSend)
            {
                UserInterface proxy = User.GetUser(u.getIPAddress(), u.getPort(), u.getName());
                usersProxy.Add(proxy);
            }

            Console.WriteLine("Creating Threads...");
            int i = 0;
            foreach (UserInterface ui in usersProxy)
            {
                ThreadInfo threadInfo = new ThreadInfo();
                threadInfo.proxy = ui;
                threadInfo.userName = ui.getName();
                threadInfo.sendUserName = User.Name;
                threadInfo.reservationMessage = reservation;
                threadInfo.threadNumber = i++;

                //send a message counter equal to the user list size to avoid further dissemination
                threadInfo.reservationMessage.messageCounter = -1;
                Thread t = new Thread(delegate()
                {
                    CallTwoPhaseCommit(threadInfo);
                });

                t.Name = threadInfo.threadNumber + " 2PC";
                localThreadList.Add(t);
                t.Start();
            }

            Console.WriteLine("Waiting for threads to finish...");
            foreach (Thread t in localThreadList)
            {
                t.Join();
            }
            Console.WriteLine("all threads have finished!");
        }
コード例 #41
0
ファイル: UserRemoteObject.cs プロジェクト: JVasques/User
        private void DisseminateInformation(ReservationMessage reservationMessage, MessageTypeToDisseminate typeOfMessage, bool secondDissemination)
        {
            Console.WriteLine("[Calling] DisseminateReservation");
            Console.WriteLine("Mode-> " + typeOfMessage.ToString());
            Console.WriteLine("");

            List<UserView> chosenUsers = null;
            if (typeOfMessage.Equals(MessageTypeToDisseminate.UPDATE_USERS_RESERVATION_INFO) || typeOfMessage.Equals(MessageTypeToDisseminate.ABORT_RESERVATION) || typeOfMessage.Equals(MessageTypeToDisseminate.COMMIT_RESERVATION)) {
                chosenUsers = reservationMessage.reservation.getUserList();
            }
            else
                chosenUsers = ChooseUsers(reservationMessage.reservation,reservationMessage.messageCounter);

            Console.WriteLine("Printing chosen users..");
            foreach (UserView u in chosenUsers) {
                Console.WriteLine(u.getName() + " port: " + u.getPort());
            }

            List<UserInterface> chosenUsersProxys = new List<UserInterface>();

            foreach (UserView u in chosenUsers) {
                UserInterface proxy = User.GetUser(u.getIPAddress(), u.getPort(), u.getName());
                chosenUsersProxys.Add(proxy);
            }

            Console.WriteLine("Creating Threads...");
            int i = 0;
            foreach (UserInterface ui in chosenUsersProxys) {
                ThreadInfo threadInfo = new ThreadInfo();
                threadInfo.proxy = ui;
                threadInfo.userName = ui.getName();  //caso
                threadInfo.sendUserName = User.Name;
                threadInfo.reservationMessage = reservationMessage;
                threadInfo.threadNumber = i++;

                if (secondDissemination) threadInfo.secondDissemination = true;
                else threadInfo.secondDissemination = false;

                Thread t;
                if (typeOfMessage.Equals(MessageTypeToDisseminate.SEND_RESERVATION)) {

                    t = new Thread(delegate() {
                         CallSendReservation(threadInfo);
                     });
                    if (secondDissemination)
                        t.Name = threadInfo.threadNumber + " SEND_RESERVATION HAS_DISSEMINATED";
                    else
                        t.Name = threadInfo.threadNumber + " SEND_RESERVATION";
                }

                else if (typeOfMessage.Equals(MessageTypeToDisseminate.UPDATE_USERS_RESERVATION_INFO)) {
                    t = new Thread(delegate() {
                        CallUpdateUsersReservationInfo(threadInfo);
                    });

                    if (secondDissemination)
                        t.Name = threadInfo.threadNumber + " UPDATE HAS_DISSEMINATED";
                    else
                        t.Name = threadInfo.threadNumber + " UPDATE";
                }

                else if (typeOfMessage.Equals(MessageTypeToDisseminate.ABORT_RESERVATION)) {
                    t = new Thread(delegate() {
                            CallAbortReservation(threadInfo);
                        });
                    t.Name = threadInfo.threadNumber + " ABORT";
                }

                else if (typeOfMessage.Equals(MessageTypeToDisseminate.COMMIT_RESERVATION))
                {
                    t = new Thread(delegate()
                        {
                            CallCommitReservation(threadInfo);
                        });
                    if (secondDissemination)
                        t.Name = threadInfo.threadNumber + " COMMIT HAS_DISSEMINATED";
                    else
                        t.Name = threadInfo.threadNumber + " COMMIT";
                }

                else if (typeOfMessage.Equals(MessageTypeToDisseminate.TWO_PHASE_COMMIT))
                {
                    t = new Thread(delegate()
                        {
                            CallTwoPhaseCommit(threadInfo);
                        });
                    if (secondDissemination)
                        t.Name = threadInfo.threadNumber + " 2PC HAS_DISSEMINATED";
                    else
                        t.Name = threadInfo.threadNumber + " 2PC";
                }
                else
                {
                    t = new Thread(delegate()
                    {
                        CallProposeSlot(threadInfo);
                    });

                    if (secondDissemination)
                        t.Name = threadInfo.threadNumber + " PROPOSE HAS_DISSEMINATED";
                    else
                        t.Name = threadInfo.threadNumber + " PROPOSE";
                }

                //needs to check if there is a thread with the same number on the list
                //if there is...remove it and add the new one (t)

                String currentThreadName = t.Name;
                char[] separator = { ' ' };
                String[] splitedThreadName = currentThreadName.Split(separator);
                String currentThreadNumber = splitedThreadName[0];
                int currentTNumber = int.Parse(currentThreadNumber);

                Thread td = ThreadExistsInThreadList(currentTNumber);

                //exists...
                if (td != null) {
                    localThreadList.Remove(td);
                }

                if (secondDissemination.Equals(true)) {

                    disseminationThreadList.Add(t);
                }
                else
                    localThreadList.Add(t);

                Console.WriteLine("Created thread " + t.Name);
                t.Start();
            }

            Console.WriteLine("Waiting for threads to finish...");
            if (secondDissemination.Equals(true)) {

                foreach (Thread t in disseminationThreadList) {
                    t.Join();
                }
            }
            else {
                foreach (Thread t in localThreadList) {
                    t.Join();
                }
            }

            Console.WriteLine("all threads have finished!");
        }
コード例 #42
0
 /// <devdoc>
 ///     Internal constructor.
 /// </devdoc>
 /// <internalonly/>
 internal ProcessThread(bool isRemoteMachine, int processId, ThreadInfo threadInfo)
 {
     _isRemoteMachine = isRemoteMachine;
     _processId = processId;
     _threadInfo = threadInfo;
 }
コード例 #43
0
ファイル: Form1.cs プロジェクト: sempers/2ch.so_Tracker
 private bool TryRecoverImage(ThreadInfo ti)
 {
     if (File.Exists("images\\" + ti.ThreadCode + ".jpg"))
     {
         try
         {
             ti.Image = Image.FromFile("images\\" + ti.ThreadCode + ".jpg");
             return true;
         }
         catch
         {
             return false;
         }                
     }
     return false;
 }
コード例 #44
0
ファイル: Form1.cs プロジェクト: sempers/2ch.so_Tracker
        public void DoUpdate(object argument, DoWorkEventArgs e)
        {
            if (Cache == null)
                Cache = new Hashtable();
            UpdateParameters _params = (UpdateParameters)e.Argument;
            List<ThreadInfo> list = new List<ThreadInfo>();
            //
            Regex repliesrgx = new Regex("Пропущено (\\d{1,3})");
            Regex imagergx = new Regex("thumb/\\d+s\\.[a-z]{3}");
            //
            string board = _params.Board;
            WebClient wcl = new WebClient();
            HtmlAgilityPack.HtmlDocument page = null;
            HtmlWeb web = new HtmlWeb();
            for (int i = 0; i <= _params.PagesNum; i++)
            {
                int totalThreads = 20 * (_params.PagesNum + 1);
                var postfix = (i == 0) ? "wakaba.html" : i.ToString() + ".html";
                try
                {
                    page = web.Load("http://2ch.so/" + board + "/" + postfix);
                }
                catch
                {
                    e.Result = null;
                    return;
                }
                int j = 1;
                foreach (var oppost in page.DocumentNode.SelectNodes("//div[@class=\"oppost\"]"))
                {
                    ThreadInfo ti = new ThreadInfo();
                    //порядок треда
                    ti.Order = i * 20 + j;
                    //номер треда
                    string threadNum = oppost.Attributes["id"].Value.Substring(5);
                    ti.ThreadCode = board + "_" + threadNum;
                    //восстановление объекта ThreadInfo из кэша
                    bool fromCache = false;
                    if (Cache.Contains(ti.ThreadCode))
                    {
                        ti = (ThreadInfo)Cache[ti.ThreadCode];
                        fromCache = true;
                    }
                    //восстановление статуса "Отслеживается"
                    ti.Track = ThreadTracks.Contains(ti.ThreadCode);
                    //восстановление статуса "Sage"
                    ti.Sage = ThreadSage.Contains(ti.ThreadCode);
                    //линк
                    ti.Link = "http://2ch.so/" + board + "/res/" + threadNum + ".html";
                    if (!fromCache)
                    {
                        //Тема
                        ti.Topic = RefineString(oppost.SelectSingleNode(".//span[@class=\"filetitle\"]").InnerText);
                        //Оп-пост
                        ti.OPPost = RefineString(oppost.SelectSingleNode(".//blockquote").InnerHtml);
                    }
                    //Количество ответов
                    var om_p = oppost.SelectSingleNode(".//span[@class=\"omittedposts\"]");
                    if (om_p == null)
                    {
                        ti.IntReplies = 1;
                    }
                    else
                    {
                        Match match = repliesrgx.Match(om_p.InnerText);
                        ti.IntReplies = int.Parse(match.Groups[1].Value) + 6;
                        //подсчет разницы в количестве постов
                        if (ti.Track && ThreadTracks.Contains(ti.ThreadCode))
                        {
                            int trackedCount = (int)ThreadTracks[ti.ThreadCode];
                            ti.Difference = ti.IntReplies - trackedCount;
                        }
                    }
                    //Картинка
                    if (!fromCache && _params.LoadImages && !ti.Sage && !TryRecoverImage(ti))
                    {
                        string path = String.Format(".//span[@id=\"exlink_{0}\"]", threadNum);
                        var img_ = oppost.SelectSingleNode(path);
                        if (img_ != null)
                        {
                            Match match = imagergx.Match(img_.InnerHtml);
                            string imageUrl = "http://2ch.so/" + board + "/" + match.Value;
                            try
                            {
                                byte[] imageData = wcl.DownloadData(imageUrl);
                                MemoryStream stream = new MemoryStream(imageData);
                                ti.Image = Image.FromStream(stream);
                                string filename = "images\\" + ti.ThreadCode + ".jpg";
                                if (!File.Exists(filename))
                                    ti.Image.Save(filename, ImageFormat.Jpeg);
                                stream.Close();
                            }
                            catch
                            {

                            }
                        }                        
                    }
                    list.Add(ti);
                    if (!fromCache)
                        Cache.Add(ti.ThreadCode, ti);
                    bgw.ReportProgress((int)((j + i * 20)*100 / totalThreads), argument);
                    j++;
                }
            }
            //пересортировка списка по приоритету (Track, Sage)
            list.Sort((t1, t2) => t1.Priority.CompareTo(t2.Priority));
            e.Result = list;            
        }
コード例 #45
0
ファイル: Report.cs プロジェクト: goldshtn/msos
 public FinalizerThreadBlocked(ThreadInfo info)
 {
     LockCount = info.Locks.Count;
     FinalizerThreadOSId = info.OSThreadId;
 }
コード例 #46
0
		internal protected void OnTargetEvent (TargetEventArgs args)
		{
			currentProcesses = null;
			
			if (args.Process != null)
				args.Process.Attach (this);
			if (args.Thread != null) {
				args.Thread.Attach (this);
				activeThread = args.Thread;
			}
			if (args.Backtrace != null)
				args.Backtrace.Attach (this);

			EventHandler<TargetEventArgs> evnt = null;
			switch (args.Type) {
			case TargetEventType.ExceptionThrown:
				lock (slock) {
					IsRunning = false;
					args.IsStopEvent = true;
				}
				evnt = TargetExceptionThrown;
				break;
			case TargetEventType.TargetExited:
				lock (slock) {
					IsRunning = false;
					IsConnected = false;
					HasExited = true;
				}
				EventHandler handler = TargetExited;
				if (handler != null)
					handler (this, args);
				break;
			case TargetEventType.TargetHitBreakpoint:
				lock (slock) {
					IsRunning = false;
					args.IsStopEvent = true;
				}
				evnt = TargetHitBreakpoint;
				break;
			case TargetEventType.TargetInterrupted:
				lock (slock) {
					IsRunning = false;
					args.IsStopEvent = true;
				}
				evnt = TargetInterrupted;
				break;
			case TargetEventType.TargetSignaled:
				lock (slock) {
					IsRunning = false;
					args.IsStopEvent = true;
				}
				evnt = TargetSignaled;
				break;
			case TargetEventType.TargetStopped:
				lock (slock) {
					IsRunning = false;
					args.IsStopEvent = true;
				}
				evnt = TargetStopped;
				break;
			case TargetEventType.UnhandledException:
				lock (slock) {
					IsRunning = false;
					args.IsStopEvent = true;
				}
				evnt = TargetUnhandledException;
				break;
			case TargetEventType.TargetReady:
				evnt = TargetReady;
				break;
			case TargetEventType.ThreadStarted:
				evnt = TargetThreadStarted;
				break;
			case TargetEventType.ThreadStopped:
				evnt = TargetThreadStopped;
				break;
			}

			if (evnt != null)
				evnt (this, args);

			EventHandler<TargetEventArgs> targetEvent = TargetEvent;
			if (targetEvent != null)
				targetEvent (this, args);
		}
コード例 #47
0
ファイル: ArchThread.cs プロジェクト: samarunraj/expressos
 private ArchThread(ThreadInfo value)
 {
     this._value = value;
 }
コード例 #48
0
ファイル: FileInfoCrawler.cs プロジェクト: kazuki/p2pncs
 void CrawlingThread()
 {
     Socket sock = null;
     ThreadInfo ti = new ThreadInfo (false, null, Thread.CurrentThread);
     lock (_connections) {
         _connections.Add (ti);
     }
     try {
         NodeHandle[] nodes = _mmlc.KeyBasedRouter.RoutingAlgorithm.GetRandomNodes (1);
         if (nodes == null || nodes.Length == 0)
             return;
         sock = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
         ti.Socket = sock;
         sock.ReceiveTimeout = sock.SendTimeout = 3000;
         sock.Connect (new IPEndPoint (((IPEndPoint)nodes[0].EndPoint).Address, nodes[0].TcpPort));
         _listener.SendMessage (sock, new Request ());
         Response res = _listener.ReceiveMessage (sock, 1024 * 1024 * 8) as Response;
         if (res != null)
             _mmlc.AppendHeader (res.Headers);
     } catch {
     } finally {
         if (sock != null) {
             try {
                 sock.Close ();
             } catch {}
         }
         lock (_connections) {
             _crawling = false;
             _connections.Remove (ti);
         }
     }
 }
コード例 #49
0
		protected override ThreadInfo[] OnGetThreads (long processId)
		{
			if (current_threads == null) {
				IList<ThreadMirror> mirrors = vm.GetThreads ();
				var threads = new ThreadInfo[mirrors.Count];
				for (int i = 0; i < mirrors.Count; i++) {
					ThreadMirror t = mirrors [i];
					string name = t.Name;
					if (string.IsNullOrEmpty (name) && t.IsThreadPoolThread)
						name = "<Thread Pool>";
					threads[i] = new ThreadInfo (processId, GetId (t), name, null);
				}
				current_threads = threads;
			}
			return current_threads;
		}
コード例 #50
0
        internal ThreadInfo Thread_GetInfo(long id)
        {
            PacketReader r = SendReceive (CommandSet.THREAD, (int)CmdThread.GET_INFO, new PacketWriter ().WriteId (id));

            ThreadInfo res = new ThreadInfo () { is_thread_pool = r.ReadByte () > 0 ? true : false };

            return res;
        }
コード例 #51
0
ファイル: FileInfoCrawler.cs プロジェクト: kazuki/p2pncs
 void Accepted(object sender, TcpListenerAcceptedEventArgs args)
 {
     Thread thrd = ThreadTracer.CreateThread (Accepted_Request, "FileInfoCrawler Send Thread");
     ThreadInfo ti = new ThreadInfo (true, args.Socket, thrd);
     lock (_connections) {
         _connections.Add (ti);
     }
     thrd.Start (ti);
 }
 public void ThreadSafeCreateAndExecuteAsync()
 {
     ThreadInfo threadInfo = new ThreadInfo();
     Thread[] threads = new Thread[10];
     for (int i = 0; i < 10; i++)
     {
         Thread thread = new Thread(new ParameterizedThreadStart(
             delegate(object obj)
             {
                 try
                 {
                     EchoAsync();
                 }
                 catch
                 {
                     ((ThreadInfo)obj).HasFailed = true;
                 }
             }));
         thread.Start(threadInfo);
         threads[i] = thread;
     }
     foreach (Thread thread in threads)
     {
         thread.Join();
     }
     Assert.IsFalse(threadInfo.HasFailed);
 }
コード例 #53
0
		internal protected virtual void OnStarted (ThreadInfo t)
		{
			if (HasExited)
				return;

			OnTargetEvent (new TargetEventArgs (TargetEventType.TargetReady) { Thread = t });

			lock (slock) {
				if (!HasExited) {
					IsConnected = true;
					foreach (BreakEvent bp in breakpointStore)
						AddBreakEvent (bp);
				}
			}
		}
コード例 #54
0
        private void SendRelationshipsInfo(IEnumerable<DocumentDetail> documentDetailList)
        {
            bool familiesLinkingRequested = _jobParameter.IsImportFamilyRelations;
            bool threadsLinkingRequested = _jobParameter.IsMapEmailThread;

            FamiliesInfo familiesInfo = familiesLinkingRequested ? new FamiliesInfo() : null;
            ThreadsInfo threadsInfo = threadsLinkingRequested ? new ThreadsInfo() : null;

            foreach (DocumentDetail doc in documentDetailList)
            {
                if (doc.docType != DocumentsetType.NativeSet)
                {
                    continue; // Only original documents may participate in relationships
                }

                string docReferenceId = doc.document.DocumentId;
                if (String.IsNullOrEmpty(docReferenceId))
                {
                    continue;
                }

                // Debug
                //Tracer.Warning("DOCID {0} corresponds to the document {1}", doc.document.FieldList[0].FieldValue, docReferenceId.Hint(4));
                //if (docReferenceId.Hint(4) == "AFE1")
                //{
                //    Tracer.Warning("STOP!");
                //}

                if (familiesLinkingRequested && !String.IsNullOrEmpty(doc.document.EVLoadFileDocumentId))
                    {
                    // We don't skip standalone documents for Families, because they always can appear to be topmost parents
                    FamilyInfo familyInfoRecord = new FamilyInfo(docReferenceId);
                    familyInfoRecord.OriginalDocumentId = doc.document.EVLoadFileDocumentId;
                    familyInfoRecord.OriginalParentId = String.IsNullOrEmpty(doc.document.EVLoadFileParentId) ? null : doc.document.EVLoadFileParentId;

                    //Tracer.Warning("SendRelationshipsInfo: OriginalDocumentId = {0}, OriginalParentId = {1}",
                    //    familyInfoRecord.OriginalDocumentId, familyInfoRecord.OriginalParentId);

                    if (String.Equals(familyInfoRecord.OriginalDocumentId, familyInfoRecord.OriginalParentId, StringComparison.InvariantCulture))
                    {
                        //Tracer.Warning("SendRelationshipsInfo: OriginalDocumentId = {0}, OriginalParentId reset to null", familyInfoRecord.OriginalDocumentId);
                        familyInfoRecord.OriginalParentId = null; // Document must not be its own parent
                    }

                    // Family has priority over thread, so if the document is part of the family we ignore its thread
                    //if (familyInfoRecord.OriginalParentId != null)
                    //{
                    //    //Tracer.Warning("SendRelationshipsInfo: OriginalDocumentId = {0}, ConversationIndex reset to null", familyInfoRecord.OriginalDocumentId);
                    //    doc.ConversationIndex = null;
                    //}
                    familiesInfo.FamilyInfoList.Add(familyInfoRecord);
                }

                // BEWARE: doc.document.ConversationIndex is not the right thing!!
                if (threadsLinkingRequested)
                {
                    // Sanitize the value
                    doc.ConversationIndex = String.IsNullOrEmpty(doc.ConversationIndex) ? null : doc.ConversationIndex;

                    // Debug
                    //Tracer.Warning("SendRelationshipsInfo: CollectionId = {0}", doc.document.CollectionId);

                    var threadInfo = new ThreadInfo(docReferenceId, doc.ConversationIndex);
                    threadsInfo.ThreadInfoList.Add(threadInfo);
                }
            }

            if (threadsLinkingRequested && threadsInfo.ThreadInfoList.Any())
            {
                SendThreads(threadsInfo);
            }

            if (familiesLinkingRequested && familiesInfo.FamilyInfoList.Any())
            {
                SendFamilies(familiesInfo);
            }
        }
コード例 #55
0
 public ThreadInfoViewModel(ThreadInfo threadInfo) {
     ThreadInfo = threadInfo;
 }
コード例 #56
0
ファイル: Report.cs プロジェクト: goldshtn/msos
        public override bool Generate(CommandExecutionContext context)
        {
            var managedThreadNames = GetManagedThreadNames(context.Heap);

            var target = context.NativeDbgEngTarget;
            IDebugSystemObjects3 sysObjects = (IDebugSystemObjects3)target.DebuggerInterface;
            sysObjects.GetCurrentProcessUpTime(out _processUpTimeInSeconds);

            var debugAdvanced = (IDebugAdvanced2)target.DebuggerInterface;
            var stackTraces = new UnifiedStackTraces(target.DebuggerInterface, context);
            foreach (var thread in stackTraces.Threads)
            {
                var stackTrace = stackTraces.GetStackTrace(thread.Index);
                var threadInfo = new ThreadInfo
                {
                    EngineThreadId = thread.EngineThreadId,
                    OSThreadId = thread.OSThreadId,
                    ManagedThreadId = thread.ManagedThread?.ManagedThreadId ?? -1,
                    SpecialDescription = thread.ManagedThread?.SpecialDescription()
                };

                string threadName;
                if (managedThreadNames.TryGetValue(threadInfo.ManagedThreadId, out threadName))
                    threadInfo.ThreadName = threadName;

                threadInfo.Fill(debugAdvanced);
                foreach (var frame in stackTrace)
                {
                    threadInfo.StackFrames.Add(new StackFrame
                    {
                        Module = frame.Module,
                        Method = frame.Method,
                        SourceFileName = frame.SourceFileName,
                        SourceLineNumber = frame.SourceLineNumber
                    });
                }
                Threads.Add(threadInfo);
            }

            RecommendFinalizerThreadHighCPU(context);
            RecommendHighNumberOfThreads();

            return true;
        }
コード例 #57
0
		//we use the Mono.Debugging classes because they are cached
		bool HasUserFrame (long tid, ThreadInfo[] infos)
		{
			foreach (var t in infos) {
				if (t.Id != tid)
					continue;
				var bt = t.Backtrace;
				for (int i = 0; i < bt.FrameCount; i++) {
					var frame = bt.GetFrame (i);
					if (frame != null && !frame.IsExternalCode)
						return true;
				}
				return false;
			}
			return false;
		}
コード例 #58
0
ファイル: Report.cs プロジェクト: goldshtn/msos
        public override bool Generate(CommandExecutionContext context)
        {
            var target = context.NativeDbgEngTarget;
            var unifiedStackTraces = new UnifiedStackTraces(target.DebuggerInterface, context);
            var blockingObjectsStrategy = new DumpFileBlockingObjectsStrategy(context.Runtime, unifiedStackTraces, target);
            foreach (var thread in unifiedStackTraces.Threads)
            {
                // This function is created lazily because we don't need the managed
                // code state for each thread.
                Func<bool> checkManagedCodeStateForThisThread = () =>
                        unifiedStackTraces.GetStackTrace(thread.EngineThreadId)
                                            .Any(f => f.Type == UnifiedStackFrameType.Managed);
                var threadWithBlockingInfo = blockingObjectsStrategy.GetThreadWithBlockingObjects(thread);
                var threadInfo = new ThreadInfo
                {
                    ManagedThreadId = threadWithBlockingInfo.ManagedThreadId,
                    OSThreadId = threadWithBlockingInfo.OSThreadId,
                    IsRunningManagedCode = checkManagedCodeStateForThisThread
                };

                foreach (var blockingObject in threadWithBlockingInfo.BlockingObjects)
                {
                    var lockInfo = new LockInfo
                    {
                        Reason = blockingObject.Reason.ToString()
                    };
                    if (blockingObject.Type == UnifiedBlockingType.ClrBlockingObject)
                    {
                        lockInfo.Object = blockingObject.ManagedObjectAddress;
                        lockInfo.ManagedObjectType = context.Heap.GetObjectType(lockInfo.Object)?.Name;
                    }
                    else
                    {
                        lockInfo.Object = blockingObject.Handle;
                        lockInfo.OSObjectName = blockingObject.KernelObjectName;
                    }
                    lockInfo.OwnerThreadOSIds.AddRange(blockingObject.OwnerOSThreadIds);
                    threadInfo.Locks.Add(lockInfo);
                }

                Threads.Add(threadInfo);

                RecommendFinalizerThreadBlocked(context);
                RecommendDeadlockedThreads();
            }

            return Threads.Any();
        }
コード例 #59
0
ファイル: ProcessInfo.cs プロジェクト: artisticcheese/MSE
        /// <summary>
        /// Update process info and thread stack traces
        /// </summary>
        /// <param name="withStack">Updates stack traces or just general info</param>
        /// <param name="allThreads">If updating stack trace should we update all of them</param>
        /// <param name="threadIds">If not updating all which ones do we update</param>
        /// <param name="depth">How many frames deep to display, 0 means show all</param>
        private void UpdateProcessInfo(bool withStack, bool allThreads, IList<int> threadIds, int depth)
        {
            processThreads.Clear();
            processCorThreads.Clear();
            generalThreadInfos.Clear();

            try
            {
                AttachAndStop();

                //build the general thread information hash
                foreach (ProcessThread gThread in generalProcessInfo.Threads)
                {
                    generalThreadInfos[gThread.Id] = gThread;
                }

                if (isAttached)
                {
                    //add the threads to an arraylist
                    foreach (CorThread cThread in debuggeeProcess.Threads)
                    {
                        try
                        {
                            ThreadInfo thread = new ThreadInfo(cThread, this);
                            if (withStack)//update stacks also
                            {
                                if (allThreads || threadIds.Contains(cThread.Id))
                                {
                                    thread.UpdateStackTrace(depth);
                                }
                            }
                            processCorThreads.Add(cThread);
                            processThreads[cThread.Id] = thread;
                        }
                        catch (KeyNotFoundException ex)
                        {
                            // This can happen if the thread died before we could get to it
                            Debug.WriteLine(ex.ToString());
                        }
                    }
                }
            }
            catch (COMException ex)
            {
                Debug.WriteLine(ex.ToString());
            }
            finally
            {
                DetachAndResume();
            }
        }
コード例 #60
0
ファイル: Report.cs プロジェクト: goldshtn/msos
        private bool HasCycle(ThreadInfo thread, HashSet<uint> visitedThreadIds)
        {
            if (visitedThreadIds.Contains(thread.OSThreadId))
                return true;

            visitedThreadIds.Add(thread.OSThreadId);

            foreach (var @lock in thread.Locks)
            {
                foreach (var ownerThreadOSId in @lock.OwnerThreadOSIds)
                {
                    var ownerThread = Threads.SingleOrDefault(t => t.OSThreadId == ownerThreadOSId);
                    if (ownerThread == null)
                        continue;

                    if (HasCycle(ownerThread, visitedThreadIds))
                        return true;
                }
            }

            return false;
        }