Daizc
count.articles51
count.tags25
count.categories3
[Csharp]Task相关

[Csharp]Task相关

async与await

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public async static void test() {
XmlConfigurator.Configure(new System.IO.FileInfo("log4net.config"));
TaskCompletionSource<string> source = new TaskCompletionSource<string>();
new Thread(o => {
log.Info("Thread Sleep");
Thread.Sleep(1000);
log.Info("Thread TrySetResult");
// source.TrySetResult("6666666666");
// source.TrySetCanceled();
source.TrySetException(new Exception("666"));
}).Start();
log.Info("Start await");
try {
string waitAsync = await source.Task.WaitAsync(new TimeSpan(0, 0, 5));
log.Info("End await => " + waitAsync);
// string s = await test2(source);
} catch (TimeoutException e) {
log.Info("TimeoutException", e);
} catch (TaskCanceledException e) {
log.Info("TaskCanceledException", e);
}
log.Info("End");
}

Task.Wait

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
public static void testWait() {
XmlConfigurator.Configure(new System.IO.FileInfo("log4net.config"));
TaskCompletionSource<string> source = new TaskCompletionSource<string>();

new Thread(o => {
log.Info("Thread Sleep");
Thread.Sleep(3000);
log.Info("Thread TrySetResult");
// source.TrySetResult("6666666666");
source.TrySetCanceled();
// source.TrySetException(new Exception());
}).Start();

log.InfoFormat("Start Wait");
try {
bool wait = source.Task.Wait(5000);
log.InfoFormat("Wait:{0}", wait);
if (wait) {
if (source.Task.Status == TaskStatus.RanToCompletion) {
log.InfoFormat("Result:{0}", source.Task.Result);
} else if (source.Task.Status == TaskStatus.Faulted) {
log.InfoFormat("Exception:{0}", source.Task.Exception);
}
} else {
log.InfoFormat("Timeout");
}
} catch (Exception e) {
log.InfoFormat("Exception: {0}=>{1}", e.GetType(),e.InnerException.GetType());
}
}

copyright.author:Daizc
copyright.permalink:https://note.bequick.run/[Csharp]Task%E7%9B%B8%E5%85%B3/
版权声明:本文采用 CC BY-NC-SA 3.0 CN 协议进行许可