Skip to content

Commit 297a2f8

Browse files
committed
add code to show how to convert async to sync
1 parent 9c0c521 commit 297a2f8

1 file changed

Lines changed: 48 additions & 1 deletion

File tree

01_Parse的多线程处理思路/Parse的底层多线程处理思路.md

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1005,6 +1005,30 @@ CYLDispatchSemaphoreTest(10384,0x112d43000) malloc: *** error for object 0x7f898
10051005
10061006
强制把异步任务转换为同步任务来方便进行单元测试。这个用途信号量是最合适的用途。但注意并不推荐应用到除此之外的其它场景!
10071007
1008+
这种异步转同步便于单元测试的用法类似于下面的写法:
1009+
1010+
1011+
```Objective-C
1012+
#define WAIT_FOREVER [self waitForStatus:XCTAsyncTestCaseStatusSucceeded timeout:DBL_MAX];
1013+
#define NOTIFY [self notify:XCTAsyncTestCaseStatusSucceeded];
1014+
```
1015+
1016+
1017+
1018+
```Objective-C
1019+
- (void)testInstallationMutated {
1020+
NSDictionary *dict = [self jsonWithFileName:@"TestInstallationSave"];
1021+
AVInstallation *installation = [AVInstallation currentInstallation];
1022+
[installation objectFromDictionary:dict];
1023+
[installation setObject:@(YES) forKey:@"enableNoDisturb"];
1024+
[installation saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
1025+
XCTAssertNil(error);
1026+
NOTIFY;
1027+
}];
1028+
WAIT;
1029+
}
1030+
```
1031+
10081032
信号量属性底层工具,他虽然非常强大,但在多数需要使用它的场合,最好从设计角度重新考虑,看是否可以不用,应该优先考虑使用诸如操作队列这样的高级工具。通常可以通过增加一个分派队列配合 `dispatch_suspend` ,或者通过其它方式分解操作来避免使用信号量。信号量并非不好,只是它本身是锁,能不使用就不用。尽量用 cocoa 框架中的高级抽象,信号量非常接近底层。所以除了上面的例子是最佳应用场景外,不推荐应用到除此之外的其它场景!
10091033

10101034

@@ -1093,9 +1117,32 @@ void dispatch_async_limit(dispatch_queue_t queue,NSUInteger limitSemaphoreCount,
10931117
}
10941118
```
10951119
1096-
10971120
你可能发现,这段代码有问题阻塞了当前线程,Demo7中也给出了改良版,可以看下。
10981121
1122+
### 为
1123+
1124+
要注意:
1125+
1126+
- 永远不要尝试在主线程上发送同步的网络请求
1127+
1128+
- 请只在后台线程中独占线程运行
1129+
1130+
这样做的风险远远超过受益。
1131+
1132+
风险如下所示:
1133+
1134+
1135+
```Objective-C
1136+
-(IBAction)cancelUpload:(id)sender {
1137+
if (_uploadTask.state == NSURLSessionTaskStateRunning) {
1138+
[_uploadTask cancel];
1139+
}
1140+
}
1141+
```
1142+
1143+
[《iOS应用的crash日志的分析基础》]( http://blog.csdn.net/jasonblog/article/details/19031517 )
1144+
[ ***Synchronous Networking On The Main Thread*** ]( https://developer.apple.com/library/ios/qa/qa1693/_index.html )
1145+
10991146
参考链接: [GitHub:Parse-SDK-iOS-OSX源码](https://github.com/ParsePlatform/Parse-SDK-iOS-OSX)
11001147

11011148
# 下篇预告:Parse的网络缓存与离线存储,敬请 star 持续关注

0 commit comments

Comments
 (0)