背景
前些天遇到一個需求,在沒有第三方原始碼的情況下,重新整理一個第三方UI,並且攔截到其ajax請求的返回結果。當結果為AVALIABLE的時候,停止重新整理並語音提示,否則繼續重新整理。
分析這個需求,發現需要控制一個重新整理迴圈的暫停與開始,因此網上搜到了通過ManualResetEvent實現執行緒的暫停與恢復。
ManualResetEvent介紹
ManualResetEvent是一個通過訊號機制,實現執行緒間狀態同步的類。常用的方法有以下三個:
WaitOne:阻止當前執行緒,直到收到訊號
Reset:將事件狀態設定為非終止狀態,導致執行緒阻止
Set:將事件狀態設定為終止狀態,從而允許繼續執行一個或多個等待執行緒
實現設計
1.通過CefSharp的谷歌瀏覽器外掛請求第三方網站
2.具體互動邏輯如下
- 預設開啟一個執行緒,並通過WaitOne掛起,等待手動開始自動重新整理的指令
- 手動通過Set方法傳送開始工作訊號
- 執行完面操作後,通過Reset將執行緒再次掛起,並等待Ajax結果,判斷Ajax結果,如果不等於AVALIABLE則再次恢復執行緒
public Form1() { InitializeComponent(); var setting = new CefSettings(); setting.Locale = "zh-CN"; setting.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36"; // 避免頁面載入不出來, 建議加上這句 Cef.Initialize(setting); workerThread = new Thread(new ThreadStart(BeginListenWorkerAsync)); workerThread.IsBackground = true; workerThread.Start(); this.停止自動監聽ToolStripMenuItem.Enabled = false; } private async void BeginListenWorkerAsync() { while (true) { _eventBeginListenWorkList.WaitOne(); //1.預設掛起執行緒,等待訊號 chromiumWebBrowser1.GetBrowser().MainFrame.ExecuteJavaScriptAsync(@"document.evaluate(""//*[@id='root']/div[1]/div[2]/div/div[2]/div[1]/div[1]/div/div[1]/button"", document).iterateNext().click()"); Thread.Sleep(1000); chromiumWebBrowser1.GetBrowser().MainFrame.ExecuteJavaScriptAsync(@"document.evaluate(""//*[@id='root']/div[1]/div[2]/div/div[1]/div/div/div/div[2]/div[6]/div/button"", document).iterateNext().click()"); _eventBeginListenWorkList.Reset(); //3.頁面執行完相應操作則再次掛起執行緒,等待ajax請求結果再判斷是否恢復執行緒 } } private void 停止自動監聽ToolStripMenuItem_Click(object sender, EventArgs e) { this.開始自動監聽ToolStripMenuItem.Enabled = true; this.停止自動監聽ToolStripMenuItem.Enabled = false; _eventBeginListenWorkList.Reset(); StartListen = false; } private void 開始自動監聽ToolStripMenuItem_Click(object sender, EventArgs e) { this.開始自動監聽ToolStripMenuItem.Enabled = false; this.停止自動監聽ToolStripMenuItem.Enabled = true; _eventBeginListenWorkList.Set(); // 2.手動通過Set傳送訊號恢復執行緒,讓其工作 StartListen = true; }
3.現在我們需要定義RequestHandler來指定ResourceHandler攔截ajax請求
private void Form1_Load(object sender, EventArgs e) { chromiumWebBrowser1.RequestHandler = new MyRequestHandler(this); chromiumWebBrowser1.Load("https://www.xxxxxxxx.com/"); }
MyRequestHandler中需要指定自定義ResourceHandler
public class MyRequestHandler : RequestHandler { Form1 _form; public MyRequestHandler(Form1 form) { _form = form; } public static string AuthorizationValue; protected override bool OnBeforeBrowse(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, bool userGesture, bool isRedirect) { // 先呼叫基類的實現,斷點除錯 return base.OnBeforeBrowse(chromiumWebBrowser, browser, frame, request, userGesture, isRedirect); } protected override IResourceRequestHandler GetResourceRequestHandler(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, bool isNavigation, bool isDownload, string requestInitiator, ref bool disableDefaultHandling) { Console.WriteLine(request.Url); if (request.Url.StartsWith("https://www.xxxxxxxxxxxxxxxx/api") && request.Headers.AllKeys.Contains("Authorization")) { AuthorizationValue = request.Headers["Authorization"]; } return new MyResourceRequestHandler(_form); } }
4.最後ResourceRequestHandler攔截到ajax請求之後,如果結果不是AVALIABLE則通過StartListenFunc再次恢復執行緒
public class MyResourceRequestHandler : ResourceRequestHandler { Form1 _form; public MyResourceRequestHandler(Form1 form) { _form = form; } private Dictionary<ulong, MemoryStreamResponseFilter> responseDictionary = new Dictionary<ulong, MemoryStreamResponseFilter>(); protected override IResponseFilter GetResourceResponseFilter(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response) { var dataFilter = new MemoryStreamResponseFilter(); responseDictionary.Add(request.Identifier, dataFilter); return dataFilter; } protected override void OnResourceLoadComplete(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response, UrlRequestStatus status, long receivedContentLength) { MemoryStreamResponseFilter filter; if (responseDictionary.TryGetValue(request.Identifier, out filter)) { var data = filter.Data; if (request.Url.StartsWith("https://xxxxxxxxxxxxxxxxxxxx/oneapi")) { var available = false; string s = System.Text.Encoding.UTF8.GetString(data, 0, data.Length); Console.WriteLine(s); if (!string.IsNullOrEmpty(s)) { var responseData = JsonConvert.DeserializeObject<ScheduleResponse>(s); if (responseData != null && responseData.productPreviews != null) { foreach (var item in responseData.productPreviews) { if (item.schedule != null && item.schedule.status != null && item.schedule.status.name == "AVAILABLE") { available = true; Mp3Player.Play(); Action act = delegate () { _form.StopListen(); }; _form.Invoke(act); break; } } } } if (!available && Form1.StartListen) { Form1.StartListenFunc(); } } filter.Dispose(); } } }
而StartListenFunc則是通過Set方法再次恢復了執行緒對ui的重複查詢
public static void StartListenFunc() { _eventBeginListenWorkList.Set(); StartListen = true; }
ManualResetEvent官方介紹如下
https://docs.microsoft.com/zh-cn/dotnet/api/system.threading.manualresetevent?view=netframework-1.1