Created
September 13, 2019 16:10
-
-
Save steveisok/d1f0a72aa51643b205858ce688c8f22d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Threading.Tasks; | |
using System.Threading; | |
using System.IO; | |
using System.Collections.Generic; | |
namespace AsyncTest | |
{ | |
class MainClass | |
{ | |
public static void Main(string[] args) | |
{ | |
AsyncPump.Run(async delegate | |
{ | |
MainClass m = new MainClass(); | |
await m.RunTask(); | |
}); | |
} | |
async Task RunTask() | |
{ | |
int originalThreadId = Thread.CurrentThread.ManagedThreadId; | |
Console.WriteLine("ThreadId={0}", Thread.CurrentThread.ManagedThreadId); | |
var fileName = Path.GetTempFileName(); | |
File.WriteAllText(fileName, "test"); | |
//new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); | |
using (Stream stream = File.OpenRead(fileName)) | |
//using (Stream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, 1024, true)) | |
{ | |
int count = (int)stream.Length; | |
byte[] buf = new byte[count]; | |
// UI thread before. | |
await stream.ReadAsync(buf, 0, count); | |
// Should continue on UI thread but continues on non-UI thread | |
// Using Task.Run instead of above ReadAsync code works. | |
//await Task.Run (() => { | |
// Thread.Sleep (400); | |
//}); | |
} | |
File.Delete(fileName); | |
int newThreadId = Thread.CurrentThread.ManagedThreadId; | |
Console.WriteLine("ThreadId={0}", Thread.CurrentThread.ManagedThreadId); | |
var val = string.Format("OriginalThreadId={0} After await: ThreadId={1}", originalThreadId, newThreadId); | |
Console.WriteLine(val); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment