Alamofire源碼導讀二:發起請求及內部加鎖的邏輯

以創建一個 DataRequest 為例子

發起請求

創建 SessionManager

順帶也創建了一個 SessionDelegate
持有一個urlSession,持有一個串行的 DispatchQueue A
注意,這個不是urlSession 回調方法執行時所在的OperationQueue

創建 Requestable 的 struct,并創建underlying 的 URLSessionDataTask

目前不太清楚作用是什么,但是文檔上的注釋寫著 Helper Types
持有一個 urlRequest
然后使用這個 Requestable,創建一個 URLSessionDataTask
注意要在SessionManager持有的串行隊列中同步創建

sessionManager 創建一個 Request 對象

通過傳入參數 URLSessionDataTaskurlSession
Request 會持有傳入的 urlSession,并根據URLSessionDataTask,創建一個 TaskDelegate。 外部對這個TaskDelegate 的讀取,被鎖保護起來了。

/// The delegate for the underlying task.
open internal(set) var delegate: TaskDelegate {get {taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() }return taskDelegate}set {taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() }taskDelegate = newValue}
}

創建 TaskDelegate

新創建的 TaskDelegate 會持有傳入的URLSessionDataTask.
在初始化方法中,會創建一個最大并發數是1的OperationQueue,并使之處于 suspend 狀態。

sessionManger 持有 Request

創建 Request 之后,會把這個 Request 加到 sessionManger 持有的一個字典中,其讀取方法也被加鎖了。

var requests: [Int: Request] = [:]
private let lock = NSLock()/// Access the task delegate for the specified task in a thread-safe manner.
open subscript(task: URLSessionTask) -> Request? {get {lock.lock() ; defer { lock.unlock() }return requests[task.taskIdentifier]}set {lock.lock() ; defer { lock.unlock() }requests[task.taskIdentifier] = newValue}
}

處理網絡數據

sessionDelegate 接受系統回調

比如方法urlSession(_, task:, didCompleteWithError:)中,會根據 URLSessionTask, 找到對應的 Request

運行 Request 所有的 validations

運行 TaskDelegate 的任務

所有的任務,都被加到了其持有的 OperationQueue 中。此時處于suspend 狀態,要使其處于可運行的狀態。
然后加到其中的所有任務,都會開始運行。

去掉對 Request 的持有

Request 已經收到并處理完了網絡回調,因此就不必被 sessionDelegate 強持有了。
如果沒有其他的持有者,Request 和其TaskDelegate 也會被釋放。

其中的同步邏輯

sessionManager 的 DispatchQueue

僅用于創建 URLSessionTask 及部分文件目錄操作,都是同步操作。
可能在任何線程創建 URLSessionTask

sessionDelegate 的 lock

僅用于對其持有的Request的讀取進行加鎖

Request 的 lock

僅對其持有的 TaskDelegate 的讀取進行加鎖

TaskDelegate 的串行 OperationQueue

其中的 Operation 在數據返回后會執行,并且不會并發。
各種 response 方法,都是在其中加入 Operation

TaskDelegate 的 lock

用于對 urlSessionTask 的讀取進行加鎖。

URLSessionTask 如何把整體串起來

  • sessionManager 中被創建
  • 初始化 Request 時被傳入,用來創建TaskDelegate
  • TaskDelegate持有
  • sessionDelegate 中,其 taskIdentifier 被作為索引,來獲取Request
  • 處理回調時,根據URLSessionTask,可以找到對應的Request,進行對應的處理。

轉載于:https://www.cnblogs.com/huahuahu/p/Alamofire-yuan-ma-dao-du-er-fa-qi-qing-qiu-ji-nei-.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/278619.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/278619.shtml
英文地址,請注明出處:http://en.pswp.cn/news/278619.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

python os.path模塊

os.path.abspath(path) #返回絕對路徑os.path.basename(path) #返回文件名os.path.commonprefix(list) #返回list(多個路徑)中,所有path共有的最長的路徑。os.path.dirname(path) #返回文件路徑os.path.exists(path) #路徑存在則返回True,路徑損壞返回Falseos.path…

讓動畫每次重復前都有延遲

動畫不從0%開始即可 keyframes textmove {20% {transform: translateX(0);}100% {transform: translateX(-100%);} }

bixby映射軟件下載_如何在Samsung Galaxy S8,S9,S10,Note 8或Note 9上重新映射Bixby按鈕...

bixby映射軟件下載We’ve said before, and we’ll say it again: Bixby sucks. You’re better off using Google Assistant any day of the week. The good news is, it’s now possible to remap the pointless Bixby button without using a third-party app. 我們之前已經…

JavaScript數據結構和算法

前言 在過去的幾年中,得益于Node.js的興起,JavaScript越來越廣泛地用于服務器端編程。鑒于JavaScript語言已經走出了瀏覽器,程序員發現他們需要更多傳統語言(比如C和Java)提供的工具。這些工具包括傳統的數據結構&…

選擇器

// 什么是 HTML 以及怎樣使用 HTML 編寫網頁 // 網頁的結構是怎樣 // 什么是 CSS 以及怎樣使用 CSS // 如何在網頁中引入 JavaScript 代碼 // 什么是 DOM, 常用 DOM API 使用 // document object model // application program interface // 什么是事件, 如何綁定事件 // // 應…

vue3打包后無法加載頁面

1、配置輸出路徑 // vue.config.js module.exports {publicPath: ./ }2、不能使用history路由 // ... export default new Router({// mode: history, routes: [{path: /,name: home,component: Home}] })

如何使用Avira Rescue CD清潔感染的PC

When you’ve got a PC completely infected with viruses, sometimes it’s best to reboot into a rescue disc and run a full virus scan from there. Here’s how to use the Avira Rescue CD to clean an infected PC. 當您的PC完全感染了病毒時,有時最好重新…

匯編語言第二章總結

第二章 寄存器 (1) 字數據在寄存器中的存放 一個字由兩個字節組成,可以存在一個16位寄存器中。 字的高8位 → 存放于通用寄存器的高8位寄存器 字的低8位 → 存放于通用寄存器的低8位寄存器。 例:十進制數據: 20000 → AX 對應的二進制…

Vue組件的三種調用方式

最近在寫fj-service-system的時候,遇到了一些問題。那就是我有些組件,比如Dialog、Message這樣的組件,是引入三方組件庫,比如element-ui這樣的,還是自己實現一個?雖然它們有按需引入的功能,但是…

axios把post的RequestPayload格式轉為formdata

方法一:配置transformRequest,缺點:其他請求格式的數據也會被重新格式化(PUT,PATCH) const service axios.create({//設置axios為form-data 方法1// headers: {// post: {// "Content-T…

火狐打印預覽_將打印和打印預覽命令添加到Firefox的上下文菜單

火狐打印預覽Have you been thinking about how much easier it would be to having the Print & Print Preview commands in Firefox’s Context Menu? The Print Context Menu extension for Firefox allows you to avoid having to use the File Menu to access the pr…

每個人都要在自己的“時區”里找到自己的快樂

祝小妹和自己生日快樂,人人都想快樂,卻在平常的365天悶悶不樂,但愿家人朋友在平常的每一天都很夠健康快樂! 在我那個開不了機的手機記事薄有句話還記得:你們不要刻意等我,因為可能現在的我還沒來得及去發現…

《2017 云計算評測報告》:帶你了解 AWS、阿里云、騰訊云等八家云計算服務提供商的綜合用戶體驗情況...

報告電子版至聽云官方博客下載:http://blog.tingyun.com/web/article/detail/1352 評測說明 評測目標:同一應用(網站)在不同云上的用戶訪問體驗,以及對云資源的使用 洞察周期及范圍:2017年4月-2017年9月 訪…

js以變量為鍵

let key "dynamic",obj{[key]:true }; obj[key2]key console.log(obj)一般在配置文件中應用較多

搭建jenkins實現自動化部署

參考: https://www.cnblogs.com/rslai/p/8135460.html轉載于:https://www.cnblogs.com/lihuanhuan/p/10612123.html

python 新聞摘要_每日新聞摘要:Microsoft內部禁止應用程序,這樣就可以了

python 新聞摘要Recently, a list of apps that Microsoft prohibits for internal employee use leaked, including Slack, Grammarly, and others. It’s tempting to think these are the actions of a company hating competition, but the truth is more complicated. 最近…

vue使用process.env搭建自定義運行環境

一、vue-cli項目下默認有三種模式: development:在 vue-cli-service serve 時使用。production:在 vue-cli-service build 和 vue-cli-service test:e2e 時使用。test:在 vue-cli-service test:unit 時使用。 對應的 process.env…

bootstrap評分插件 Bootstrap Star Rating Examples

http://www.jq22.com/demo/bootstrap-star-rating-master201708041812/ 轉載于:https://www.cnblogs.com/waw/p/8288951.html

http 請求報文

1、報文 2、http請求方法 restful接口 post:創建 put:更新 轉載于:https://www.cnblogs.com/mengfangui/p/10171559.html

chrome硬件加速_如何在Chrome中打開和關閉硬件加速

chrome硬件加速Google Chrome comes equipped with hardware acceleration, a feature which takes advantage of your computer’s GPU to speed up processes and free vital CPU time. However, sometimes driver incompatibilities can cause this feature to misbehave an…