Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

增加新的Demo #1

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
调整输出
jarenduan committed Jul 12, 2017
commit bcc5bb3cbd7d07954cac92b44e4cf37f7fd8ce20
33 changes: 18 additions & 15 deletions ijw.Demo.AsyncThread/Program.cs
Original file line number Diff line number Diff line change
@@ -6,12 +6,13 @@

namespace ijw.Demo.AsyncThread {
class Program {
static int count = 0;
private static string LargeString = null;
private static int count = 0;
private static string LargeString = string.Empty;
private static Random r = new Random();

static void Main(string[] args) {
Console.WriteLine("Main Start...");
while(count < 100) {
while (count < 100) {
count++;
dosomeIO(count);
}
@@ -37,25 +38,27 @@ private async static void dosomething(int i) {
}

private async static void dosomeIO(int i) {
Console.WriteLine("Thread " + Thread.CurrentThread.ManagedThreadId.ToString() + " start async work " + count.ToString());
int oldThread = Thread.CurrentThread.ManagedThreadId;
Console.WriteLine("Thread " + oldThread.ToString() + " start async work " + count.ToString() + " with string of " + LargeString.Length + "...");

using (StreamWriter sw = new StreamWriter("file"+i.ToString()+".txt", false)) {
await sw.WriteLineAsync(buildLargeString());
using (StreamWriter sw = new StreamWriter("file" + i.ToString() + ".txt", false)) {
await sw.WriteLineAsync(buildString());
}

//下面的代码,根据完成task的时间,有可能是在另外的线程中进行的
//即,await 前后的代码被分成了两个部分,所等待的操作如果没有马上完成就立即返回,待完成后抓一个线程继续进行后面的代码
//await内部在有必要的时候使用线程池,对异步开发者屏蔽了线程调用的细节
Console.WriteLine(" Thread " + Thread.CurrentThread.ManagedThreadId.ToString() + " finish async work " + i.ToString());

string buildLargeString() {
if (LargeString == null) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < 40000; j++) {
sb.Append(j.ToString());
}
LargeString = sb.ToString();
int newThread = Thread.CurrentThread.ManagedThreadId;
Console.WriteLine(" Thread " + newThread.ToString() + " finish async work " + i.ToString() + ". " + ((oldThread == newThread) ? String.Empty : "(Different thread)"));

string buildString()
{
StringBuilder sb = new StringBuilder();
var length = r.Next(4000);
for (int j = 0; j < length; j++) {
sb.Append(j.ToString());
}
LargeString = sb.ToString();
return LargeString;
}
}