-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDiary7.txt
786 lines (685 loc) · 22.9 KB
/
Diary7.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
【2019-05-22】pyinstaller
pyinstaller可以把py文件转化为可执行文件
可以使用pyi-makespec生成中间文件,再用pyinstaller转化为可执行文件
也可以使用直接pyinstaller转化为可执行文件
注意使用--hidden-import参数保证隐式import的模块也被打包
# https://pythonhosted.org/PyInstaller/man-pages.html
# https://blog.csdn.net/king_mountian/article/details/81664599
例:
import os
import subprocess
def makespec(outname):
# 直接转化为可执行文件
# cmd = "pyinstaller"
cmd = "pyi-makespec"
args = [cmd]
base = "."
# 把所有的模块都加入到-hidden-import里
for root, dirs, files in os.walk(base):
for name in files:
if name.endswith(".py"):
module = root.replace("\\", ".").lstrip(".")
if module:
hidden_import = module + "." + name[:-3]
else:
hidden_import = name[:-3]
args.append("--hidden-import=%s" % hidden_import)
args.append("-F")
res = os.path.abspath("res").replace("\\", "/")
args.append("--paths=%s" % res)
args.append("-n%s" % outname)
args.append("makelink_gui.py")
subprocess.call(args, shell=True)
def build():
name = "MakeLink"
makespec(name)
subprocess.call(r"pyinstaller %s.spec" % name, shell=True)
def main():
build()
if __name__ == '__main__':
main()
【2019-05-23】【1】python print >> 重定向
# https://blog.csdn.net/xyh421/article/details/79513259
这种方式基于print语句的扩展形式
即print >> obj, expr
其中,obj为一个file-like(尤其是提供write方法的)对象
为None时对应标准输出(sys.stdout) expr将被输出到该文件对象中
例:
class SysOutHooker(object):
def __init__(self, org):
self.org = org
def write(self, msg):
msg = msg.rstrip("\r\n")
if not msg:
return
self.org.write("hooker: %s\n" % msg)
hooker = SysOutHooker(sys.stdout)
print >> hooker, "test message"
print "test message"
输出:
hooker: test message
test message
【2019-05-23】【2】python subprocess 重定向
# https://www.cnblogs.com/zhoug2020/p/5079407.html
subprocess.Popen传入stdout, stderr控制子进程重定向
stdout = None 或者 stderr = None 表示子进程不会做任何重定向工作 子进程的文件描述符会继承父进程的
stderr = subprocess.STDOUT 表示子进程的标准错误也输出到标准输出
stdout = subprocess.PIPE 或者 stderr = subprocess.PIPE 则表示需要创建一个新的管道给子进程进行重定向
对sys.stdout和sys.stderr指定fileobj不会影响到进程的重定向
只会影响到python里输出的重定向
比如普通print之于sys.stdout traceback之于sys.stderr
例:
test.py [win32]:
class SysOutHooker(object):
def __init__(self, org):
self.org = org
def write(self, msg):
pass
# 这里是设置python输出钩子 不是进程输出重定向
hooker = SysOutHooker(sys.stdout)
sys.stdout = hooker
err_hooker = SysOutHooker(sys.stderr)
sys.stderr = err_hooker
print "set stderr = None: "
# subprocess.Popen 设置的stdout stderr 继承父进程 即是控制台输出
p = subprocess.Popen(["echo", "echo test"], shell = True, stdout = None, stderr = None, universal_newlines = True)
p = subprocess.Popen(["wrongcommand"], shell = True, stdout = None, stderr = None, universal_newlines = True)
p.wait()
print "p.stdout", p.stdout
print "p.stderr", p.stderr
print "set stderr = subprocess.STDOUT: "
# subprocess.Popen 设置的stdout继承父进程 stderr定向到stdout 即是控制台输出
p = subprocess.Popen(["echo", "echo test"], shell = True, stderr = subprocess.STDOUT, universal_newlines = True)
p = subprocess.Popen(["wrongcommand"], shell = True, stderr = subprocess.STDOUT, universal_newlines = True)
p.wait()
print "p.stdout", p.stdout
print "p.stderr", p.stderr
print "set stderr = subprocess.PIPE: "
# subprocess.Popen 设置的stdout stderr 输出到管道中
p = subprocess.Popen(["echo", "echo test"], shell = True, stdout = subprocess.PIPE, stderr = subprocess.PIPE, universal_newlines = True)
p = subprocess.Popen(["wrongcommand"], shell = True, stdout = subprocess.PIPE, stderr = subprocess.PIPE, universal_newlines = True)
p.wait()
print "p.stdout", p.stdout
print "p.stderr", p.stderr
【执行 python test.py】:
输出:
"echo test"
'wrongcommand' 不是内部或外部命令,也不是可运行的程序
或批处理文件。
"echo test"
'wrongcommand' 不是内部或外部命令,也不是可运行的程序
或批处理文件。
【执行 python test.py 2> nul 2>&1】
输出:
"echo test"
'wrongcommand' 不是内部或外部命令,也不是可运行的程序
或批处理文件。
"echo test"
'wrongcommand' 不是内部或外部命令,也不是可运行的程序
或批处理文件。
【执行 python test.py > nul 2>&1】:
没有任何输出
【2019-05-23】【2】python subprocess 重定向到PIPE卡死
# https://blog.csdn.net/xiaoxianerqq/article/details/78864330
# https://www.cnblogs.com/chybot/p/5176118.html
使用subprocess.Popen 重定向到subprocess.PIPE 如果管道内容太多
而且使用wait等待子进程结束 则可能会卡死
所以使用PIPE时不要使用wait而要使用communicate
【2019-05-26】创建与删除软链接和硬链接
1.linux
1.1 给文件创造硬链接
ln SourceFile DestFile
1.2 给文件创造软链接
ln -s SourceFile DestFile
1.3 给文件夹创造硬链接(通常都会因为操作系统链接机制限制而失败[操作系统不支持])
ln -d SourceFolder DestFolder
1.4 给文件夹创造软链接
ln -s SourceFolder DestFolder
2.windows
2.1 给文件创造硬链接
mkdir /H DestFile SourceFile
2.2 给文件创造软链接
mkdir DestFile SourceFile
2.3 给文件夹创造硬链接 [操作系统不支持]
2.4 给文件夹创造软链接
mkdir /D DestFile SourceFile
3.python下删除符号链接目录坑
在windows下给文件夹创建软链接后
如果用python的shutil.rmtree删除链接结果 会导致即使删除后目标文件夹(链接结果)被删除
源文件夹还保留 但是源文件夹里的文件与文件夹会全部丢失 这个应该是shutil.rmtree的bug
如果使用os.remove则会报WindowsError: [Error 5]
如果使用os.removedirs(其本身功能为只能递归删除空文件夹)则不会出现此问题
linux下如果调用os.removedirs会报OSError: [Errno 20] Not a directory
调用shutil.rmtree则会报raise OSError("Cannot call rmtree on a symbolic link")
os.remove则不会报任何错误
另外python的os.symlink只有在linux下有效 在windows下连接口都没有
所以对链接的操作最好还是调用bat命令或者shell命令执行
windows下
删除符号链接目录 rmdir DestFolder
删除符号链接文件 del DestFile
linux下符号链接目录与符号链接文件 rm DestFolder
4.删除源文件坑
还有无论windows下还是linux下给一个文件(设为Source)创建了硬链接(设为HardResult)
和软链接(设为SoftResult)后 此时即使源文件在操作系统的引用计数已经+1了
但是如果删除了源文件(Source)后 软链接(SoftResult)还是会实效
证明软链接在两个操作系统上都是根据路径来链接的
【2019-05-30】【1】python subprocess 重定向到PIPE同时一直取出PIPE的输出
out = []
err = []
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
for line in iter(p.stdout.readline, b''):
line = line.rstrip('\n')
line = line.rstrip('\r')
out.append(line)
out = '\n'.join(out)
p.stdout.close()
for line in iter(p.stderr.readline, b''):
line = line.rstrip('\n')
line = line.rstrip('\r')
err.append(line)
err = '\n'.join(err)
p.stderr.close()
p.wait()
【2019-05-30】【2】Qt使用QStandardItemModel实现自定义树形控件需求
TEST_NODE = {
'src':
{
'Package':
{
'Char': {},
'MapConfig': {},
'Repository': {},
'Text': {},
'Sounds': {},
'Video':{},
'Worlds': {}
}
},
'res':{}
}
# Qt QStandardItemModel封装了大部分树形model需要的需求
# QStandardItemModel使用到了QStandardItem控件
# 可以通过QStandardItem控件的setData(..., QtCore.Qt.UserRole)设置userdata
# 可以使用itemFromIndex接口从index获取具体QStandardItem
# 通过QStandardItem的data接口从而获取到控件的userdata
class MyTreeModel(QtGui.QStandardItemModel):
def __init__(self, parent, dict_data):
super(MyTreeModel, self).__init__()
self.dict_data = dict_data
self.build(self.invisibleRootItem(), self.dict_data)
def build(self, parent_item, dict_data):
for key, value in dict_data.iteritems():
item = QtGui.QStandardItem(key)
item.setData(value, QtCore.Qt.UserRole)
parent_item.appendRow(item)
self.build(item, value)
# 如果使用直接使用QAbstractItemModel实现树形model需要的需求会十分麻烦
# 因为通常要在QAbstractItemModel返回的QModelIndex存下internalPointer
# 而python里创建QModelIndex传入python对象作为指针通常会闪退
# 而且还要实现一些QAbstractItemModel的纯虚函数
# class MyTreeModel(QtCore.QAbstractItemModel):
# def __init__(self, parent, dict_data):
# super(MyTreeModel, self).__init__()
# self.dict_data = dict_data
# def index(self, row, column, parent_index):
# ret = self.createIndex(row, column)
# return ret
# def parent(self, child_index):
# return QtCore.QModelIndex()
# def columnCount(self, parent_index):
# return 1
# def rowCount(self, parent_index):
# if not parent_index.isValid():
# return 1
# return 0
# def data(self, index, role):
# if role == QtCore.Qt.DisplayRole:
# return "Test"
class MyTreeView(QtGui.QTreeView):
def mouseReleaseEvent(self, mouse_event):
if mouse_event.button() == QtCore.Qt.RightButton:
selected_idx_list = self.selectionModel().selectedRows(0)
for selected_idx in selected_idx_list:
item = self.model().itemFromIndex(selected_idx)
variant_obj = item.data(QtCore.Qt.UserRole)
user_data = variant_obj.toPyObject()
return super(MyTreeView, self).mouseReleaseEvent(mouse_event)
class MainWindow(QtGui.QWidget):
def __init__(self, app):
QtGui.QWidget.__init__(self)
self.m_model = MyTreeModel(self, TEST_NODE)
self.m_treeview = MyTreeView(self)
self.m_treeview.setModel(self.m_model)
self.m_treeview.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
self.m_treeview.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
self.resize(1024, 550)
class TestApp(QtGui.QApplication):
def __init__(self, arg):
super(TestApp, self).__init__(arg)
def init(self):
self.setStyleSheet(qdarkstyle.load_stylesheet_pyqt())
self.main_window = MainWindow(self)
self.main_window.show()
def main():
APP = TestApp(sys.argv)
APP.init()
sys.exit(APP.exec_())
if __name__ == "__main__":
main()
【2019-06-02】【1】shell for looping
1.for ((i=v1; i <= v3; i=i+1))
for ((i=1; i <= 3; i=i+1)); do
echo $i
done
2.for i in {v1..v3}
for i in {1..3}; do
echo $i
done
3.for i in v1 v2 v3
for i in 1 2 3; do
echo $i
done
4.
当使用for i in v1 v2 v3...时候
IFS是作用于每个变量上(v1 v2 v3...)
当使用for i in $v时候
IFS是作用于变量v上
所以for中空格固定作为参数分割符号
IFS作用于迭代中的每个变量
example:
data=1,2,3
# IFS作用于1,2,3 默认IFS没有起到作用
for i in 1,2,3; do
echo $i
done
# IFS作用于data 默认IFS没有起到作用
for i in $data; do
echo $i
done
IFS=,
# IFS作用于1,2,3 IFS起到作用分割了1,2,3
# 1 2 3整体作为一个参数赋到i
for i in 1,2,3; do
echo $i
done
# IFS作用于data IFS起到作用分割了1,2,3
# 1 2 3分别作为参数赋到i
for i in $data; do
echo $i
done
output:
# IFS作用于1,2,3 默认IFS没有起到作用
1,2,3
# IFS作用于data 默认IFS没有起到作用
1,2,3
# IFS作用于1,2,3 IFS起到作用分割了1,2,3
# 1 2 3整体作为一个参数赋到i
1 2 3
# IFS作用于data IFS起到作用分割了1,2,3
# 1 2 3分别作为参数赋到i
1
2
3
【2019-06-02】【2】shell array
1.define a array
array=('that' 'is' '')
2.index a array
array[0]='this'
3.append a variable in a array, not necessarily in the end of the array
array[4]='test'
array[3]='a'
4.another way to append variable into a array
array+=('!')
5.loop a array
for str in ${array[*]}; do
echo $str
done
example:
array=('that' 'is' '')
# index a variable in array
array[0]='this'
echo 'echo ${array[0]}'
echo ${array[0]}
# append a variable in a array, not necessarily in the end of the array
array[4]='test'
# append a variable in the position that more than the end of the array
# the variable between the new variable and previous last variable
# become empty
echo 'echo ${array[3]}'
echo ${array[3]}
array[3]='a'
echo 'echo ${array[4]}'
echo ${array[4]}
# append another array into a array
# array+=('!')
var='!'
array+=($var)
echo
echo 'loop echo'
for str in ${array[*]}; do
echo $str
done
output:
echo ${array[0]}
this
echo ${array[3]}
echo ${array[4]}
test
loop echo
this
is
a
test
!
【2019-06-02】【3】shell array
1.define a array, element can be split by space, linebreak or tab
array=('that' 'is' 'not'
'a'
'test'
)
2.delete a element of a array
unset array[3]
3.get the length of a array
echo ${#array[@]}
4.get the length of a element of a array
echo ${#array[1]}
5.sort the element of a array by using sort
sort_array=($(for ele in ${array[*]}; do
echo $ele
done | sort))
example:
# element can be split by space, linebreak or tab
array=('that' 'is' 'not'
'a'
'test'
)
# delete a element of a array
unset array[3]
# get the length of a array
echo ${#array[@]}
# get the length of a element of a array
echo ${#array[1]}
# sort the element of a array by using sort
sort_array=($(for ele in ${array[*]}; do
echo $ele
done | sort))
for ele in ${sort_array[*]}; do
echo $ele
done
output:
4
2
is
not
test
that
【2019-06-13】python zip
# https://www.runoob.com/python/python-func-zip.html
python zip函数可以把多个列表或者元组(广义上为可迭代的对象)压缩成一个列表(设为zip_result)
压缩方式是使返回列表的每一个索引上元素都为传入列表或者元组的的对应索引上的元素组成的元组
注意如果传入列表或者元组长度不一致 则返回列表长度与最短的对象相同
然后可以再通过调用zip函数传入参数 *zip_result 可以获取另一个返回列表
返回列表对应索引上的元组则第一次调用zip时候传入的列表或元组
例:
a = [1, 2, 3]
b = ['a', 'b', 'c']
c = [100.0, 200.0, 300.0]
zip_result = zip(a, b, c)
print zip_result
d = zip(*zip_result)
print d
输出:
[(1, 'a', 100.0), (2, 'b', 200.0), (3, 'c', 300.0)]
[(1, 2, 3), ('a', 'b', 'c'), (100.0, 200.0, 300.0)]
【2019-07-13】【1】shell positional parameter
1.$0 represent the path of the shell
2.${10} the get of value of the parameter the index is bigger than 9
3.shift to move the second place parameter the the first place
example:
shell.sh:
echo "path of the shell is $0"
sum=0
while [[ $# -gt 0 ]]; do
sum=$((sum + $1))
# move the parameter from the secnod place to firsrt place
# (zero place is reserved for the path of the srcipt)
shift
done
echo "sum of parameters is $sum"
./shell.sh 1 2 3
output:
path of the shell is ./shell.sh
sum of parameters is 6
【2019-07-13】【2】ubuntu安装JDK
https://www.cnblogs.com/chenfq/p/8250823.html
https://blog.csdn.net/tiryzheng/article/details/79427949
1.到JDK官网https://www.oracle.com/technetwork/articles/javase/index-jsp-138363.html下载对应版本.deb安装包
2.安装JDK对应.deb,使用sudo dpkg -i *.deb或者直接在资源浏览器里双击.deb文件在ubuntu软件中心安装
3.打开~/.bashrc文件,追加内容
JAVA_HOME=/usr/lib/jvm/jdk-12.0.1
JRE_HOME=$JAVA_HOME/jre
JAVA_BIN=$JAVA_HOME/bin
CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar:$JRE_HOME/lib
PATH=$PATH:$JAVA_HOME/bin:$JRE_HOME/bin
export JAVA_HOME JRE_HOME PATH CLASSPATH
(其中JAVA_HOME为JDK安装位置,使用.deb方式安装后java默认会放在/usr/lib/jvm/里)
4.source ~/.bashrc使之立即生效
5.java -version检验安装是否成功
【2019-07-31】c# async wait
// https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/concepts/async/index#dont-block-await-instead
// https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/keywords/async
// https://cloud.tencent.com/developer/article/1445420
1.await表达式后的代码为将被异步执行的代码,但实际上await并不会真正创建一个线程,
Task.Run才会真正创建一个线程。因此如果await后的代码不是Task.Run的返回值,则不会达到真正创建线程的目的。
(即使没有await关键字,Task.Run也会创建线程,但线程是否会被创建,取决于编译器的优化)
2.await表达式部分后的代码函数会在执行完异步函数后在异步线程环境里继续执行,直到遇到另一个await表达式。
3.函数头里async关键字表示该函数存在异步调用,在调用后线程环境发生切换,因此里面必须存在await关键字。
4.async函数存在3种类型的返回值。void,Task,Task<T>
意义分别是直接退出控制流,设置 Task 的属性并退出,设置Task的属性和返回值(Result 属性)并退出。
5.线程是否会被创建,取决于编译器的优化。如果只是对Task.Run的返回值执行await,编译器则可能把需要在新的异步线程里
执行的代码在已经创建好的线程里执行,如果是对Task.Run返回的Task对象执行Wait,此时由于所有由Task创建的线程均
不能被释放,这样会促使Task.Run创建与调用次数相同的线程。
例:
1.
static void Main(string[] args)
{
string tid = Thread.CurrentThread.ManagedThreadId.ToString();
Console.WriteLine($"PreMain tid {tid}");
Task t = TestAsynsFake();
t.Wait();
tid = Thread.CurrentThread.ManagedThreadId.ToString();
Console.WriteLine($"PostMain call tid {tid}");
}
public static async Task TestAsynsFake(int depth = 0)
{
if (depth > 10)
return;
string tid = Thread.CurrentThread.ManagedThreadId.ToString();
Console.WriteLine($"TestAsynsFake call dpeth:{depth} tid:{tid}");
await TestAsynsFake(depth + 1);
}
输出:
// 并没有真正创建出线程
PreMain tid 1
TestAsynsFake call dpeth:0 tid:1
TestAsynsFake call dpeth:1 tid:1
TestAsynsFake call dpeth:2 tid:1
TestAsynsFake call dpeth:3 tid:1
TestAsynsFake call dpeth:4 tid:1
TestAsynsFake call dpeth:5 tid:1
TestAsynsFake call dpeth:6 tid:1
TestAsynsFake call dpeth:7 tid:1
TestAsynsFake call dpeth:8 tid:1
TestAsynsFake call dpeth:9 tid:1
TestAsynsFake call dpeth:10 tid:1
PostMain call tid 1
2.
static void Main(string[] args)
{
string tid = Thread.CurrentThread.ManagedThreadId.ToString();
Console.WriteLine($"PreMain tid {tid}");
Task t = TestAsync();
t.Wait();
tid = Thread.CurrentThread.ManagedThreadId.ToString();
Console.WriteLine($"PostMain call tid {tid}");
}
public static async Task TestAsync(int depth = 0)
{
if (depth > 10)
return;
var t = Task.Run(async () =>
{
string tid = Thread.CurrentThread.ManagedThreadId.ToString();
Console.WriteLine($"TestAsync call dpeth:{depth} tid:{tid}");
await TestAsync(depth + 1);
});
await t;
}
输出:
// 有创建线程但不是所有async函数都创建了线程
PreMain tid 1
TestAsync call dpeth:0 tid:3
TestAsync call dpeth:1 tid:4
TestAsync call dpeth:2 tid:4
TestAsync call dpeth:3 tid:4
TestAsync call dpeth:4 tid:4
TestAsync call dpeth:5 tid:4
TestAsync call dpeth:6 tid:4
TestAsync call dpeth:7 tid:4
TestAsync call dpeth:8 tid:4
TestAsync call dpeth:9 tid:4
TestAsync call dpeth:10 tid:4
PostMain call tid 1
3.
static void Main(string[] args)
{
string tid = Thread.CurrentThread.ManagedThreadId.ToString();
Console.WriteLine($"PreMain tid {tid}");
Task t = TestAsyncReal();
t.Wait();
tid = Thread.CurrentThread.ManagedThreadId.ToString();
Console.WriteLine($"PostMain call tid {tid}");
}
public static async Task TestAsyncReal(int depth = 0)
{
if (depth > 10)
return;
var t = Task.Run(async () =>
{
string tid = Thread.CurrentThread.ManagedThreadId.ToString();
Console.WriteLine($"TestAsyncReal call dpeth:{depth} tid:{tid}");
await TestAsyncReal(depth + 1);
});
t.Wait();
// keep the compiler happy
await t;
}
输出:
// 所有async函数都创建了线程
PreMain tid 1
TestAsyncReal call dpeth:0 tid:3
TestAsyncReal call dpeth:1 tid:4
TestAsyncReal call dpeth:2 tid:5
TestAsyncReal call dpeth:3 tid:6
TestAsyncReal call dpeth:4 tid:7
TestAsyncReal call dpeth:5 tid:8
TestAsyncReal call dpeth:6 tid:9
TestAsyncReal call dpeth:7 tid:10
TestAsyncReal call dpeth:8 tid:11
TestAsyncReal call dpeth:9 tid:12
TestAsyncReal call dpeth:10 tid:13
PostMain call tid 1
4.
static void Main(string[] args)
{
string tid = Thread.CurrentThread.ManagedThreadId.ToString();
Console.WriteLine($"PreMain tid {tid}");
TestTask();
tid = Thread.CurrentThread.ManagedThreadId.ToString();
Console.WriteLine($"PostMain call tid {tid}");
}
public static void TestTask()
{
var t = Task.Run(() =>
{
string tid = Thread.CurrentThread.ManagedThreadId.ToString();
Console.WriteLine($"TestTask calltid:{tid}");
});
t.Wait();
}
输出:
// 没有await关键字照样创建线程,该线程由Task.Run创建
PreMain tid 1
TestTask calltid:3
PostMain call tid 1
【2019-08-06】c# 委托
// https://www.cnblogs.com/wanglla/p/4257135.html
委托delegate是一种特殊类型,基类为System.Delegate,通过C#特殊语法糖创建
事件是一种特殊的委托类型实例,只能够在持有事件的对象内部发起广播
例:
public class Test
{
// 自定义委托类型
public delegate void IntCallDelegate(int x);
// 定义自定义委托类型对象
public IntCallDelegate Delegate;
// 定义Delegate对象 所有委托类型都派生于System.Delegate
public Delegate GeneralDelegate;
// 特殊委托对象 只能够在持有该对象的对象内部发起广播
public event IntCallDelegate Event;// = new IntCallDelegate((x) => { });
public Test()
{
}
public void IntTest(int x)
{
Console.WriteLine($"ClassTest:{x}");
}
public void RaiseEvent(int x)
{
Event(x);
}
}
class Program
{
static private Test c;
static void Main(string[] args)
{
c = new Test();
Console.WriteLine("----- DELEGATE -----");
c.Delegate += new Test.IntCallDelegate(c.IntTest);
c.Delegate += new Test.IntCallDelegate(IntTest);
c.Delegate(10);
Console.WriteLine("----- EVENT -----");
c.Event += new Test.IntCallDelegate(c.IntTest);
c.Event += new Test.IntCallDelegate(IntTest);
// 不允许
//c.Event(20);
c.RaiseEvent(20);
Console.WriteLine("----- GENERAL DELEGATE -----");
Type type = null;
MethodInfo info = null;
type = c.GetType();
info = type.GetMethod("IntTest");
//c.GeneralDelegate = Delegate.CreateDelegate(typeof(ClassTest.IntCallDelegate), c, info);
// 使用 Delegate类Combine接口 添加处理函数
c.GeneralDelegate = Delegate.Combine(c.GeneralDelegate, Delegate.CreateDelegate(typeof(Test.IntCallDelegate), c, info));
info = typeof(Program).GetMethod("IntTest", BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
c.GeneralDelegate = Delegate.Combine(c.GeneralDelegate, Delegate.CreateDelegate(typeof(Test.IntCallDelegate), info));
// 使用 Delegate类DynamicInvoke接口 促发delegate广播
c.GeneralDelegate.DynamicInvoke(30);
}
static void IntTest(int x)
{
Console.WriteLine($"Program:{x}");
}
}
输出:
----- DELEGATE -----
ClassTest:10
Program:10
----- EVENT -----
ClassTest:20
Program:20
----- GENERAL DELEGATE -----
ClassTest:30
Program:30