static void AwaitAsyncAdvancedDemo() { #region task and await Console.WriteLine("Thread {0},主线程", Thread.CurrentThread.ManagedThreadId); AsyncAwaitDemo asyncawaitdemo = new AsyncAwaitDemo(); asyncawaitdemo.AwaitMethod(); #region await & task.GetAwaiter() difference //asyncawaitdemo.TaskMethod(); //asyncawaitdemo.TaskMethod2(); #endregion #region await 本质 //asyncawaitdemo.AwaitTaskMethod(); #endregion Console.ReadKey(); #endregion }
static void Main(string[] args) { var demo = new AsyncAwaitDemo(); demo.DoStuff(); while (true) { Console.WriteLine("Doing Stuff on the Main Thread..................."); } }
static void Main() { var demo = new AsyncAwaitDemo(); demo.DoStuff(); while (true) { Thread.Sleep(100); Console.WriteLine("Doing Stuff on the Main Thread..................."); } }
static void AwaitAsyncSimpleDemo2() { AsyncAwaitDemo asyncawaitdemo = new AsyncAwaitDemo(); // 同步方式 Console.WriteLine("同步方式测试开始!"); asyncawaitdemo.SyncMethod(0); Console.WriteLine("同步方式结束!"); Console.ReadKey(); // 异步方式 Console.WriteLine("\n异步方式测试开始!"); asyncawaitdemo.AsyncMethod(0); Console.WriteLine("异步方式结束!"); Console.ReadKey(); }
public static void Main(string[] args) { // String Fromat // StringFormatDemo.ShowFloatNumber(); // -- Async Await // AsyncAwaitDemo.ButtonClick1(); AsyncAwaitDemo.ButtonClick2(); // AsyncAwaitDemo.ButtonClick2_Wrong(); // Console.ReadLine(); // Wait the async function. // -- Thread // MultiThreadDemo.TwoThreads(); //-- Regex // RegexDemo.Replace(); //RegexDemo.FindFirst(); //RegexDemo.FindAll(); }
static void Main(string[] args) { var xs = new List <int>() { 1, 5, 2, 3, 4 }; var ys = Filter <int>(xs, x => x % 2 == 0); List <Artist> artists = new List <Artist>(); artists.Add(new Artist("Test")); artists.Add(new Artist("asdf")); artists.Add(new Artist("Falco")); artists.Add(new Artist("newArtist")); artists.Add(new Artist("Falcon")); artists.Add(new Artist("Falcone")); var artistsFiltered = artists.Where(o => o.Name.Contains("Falco")); foreach (Artist art in artistsFiltered) { Console.WriteLine(art.Name); } PullExample.Run(); PushExample.Run(); PushExampleWithSubject.Run(); var oneNumberPerSecond = Observable.Interval(TimeSpan.FromSeconds(1)); var lowNums = from n in oneNumberPerSecond where n < 5 select n; Console.WriteLine("Numbers < 5:"); lowNums.Subscribe(lowNum => { Console.WriteLine(lowNum); }); var t2 = new Thread(() => { int i = 1000; while (i < 1010) { Console.WriteLine(i++); } }); t2.Start(); TasksExample.Run(); NewTaksExample.Run(); var asyncawait = new AsyncAwaitDemo(); #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed asyncawait.DoStuff(); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed int a = 0; while (a < 10) { Console.WriteLine("Do something AsyncAwait"); a++; } oneNumberPerSecond = Observable.Interval(TimeSpan.FromSeconds(1)); var stringsFromNumbers = from n in oneNumberPerSecond select new string('*', (int)n); Console.WriteLine("Strings from numbers:"); stringsFromNumbers.Subscribe(num => { Console.WriteLine(num); }); }
static void Main(string[] args) { var versionInf = new VersionInfo("old", "xref"); Filter(versionInf); var content = GetConfig <BuildConfig>(@"C:\TestFiles\xrefmap\docfx.temp.json"); var def = BranchNames.DefaultBranches; var branch1 = MappingBranch("live-sxs"); var ps = Path.Combine("/", "/basepath", "ab"); Uri uri; if (Uri.TryCreate("http://www.abc.com/base/a.html", UriKind.Relative, out uri)) { Console.WriteLine("is relative"); } var versionFolder = new VersionInfo("folder", null); File.WriteAllText(@"C:\TestFiles\xrefmap\filemap.now.json", JsonUtility.ToJsonString(versionFolder, true)); var paths = new List <string> { "1", "2" }; var joinedPath = string.Join(", ", paths); var dict = new Dictionary <int, int>(); dict.Add(0, 0); dict.Add(1, 1); dict.Add(2, 2); dict.Remove(0); dict.Add(10, 10); foreach (var entry in dict) { Console.WriteLine(entry.Key); } Dictionary <string, VersionInfo> versionInfo = new Dictionary <string, VersionInfo> { { "testMoniker-1.0_justfortest", new VersionInfo("v2.0/", null) }, { "testMoniker-1.1_justfortest", new VersionInfo("v2.1/", null) } }; var xrefmaps = new List <string> { "xrefmap.yml", "testMoniker-1.0_justfortest.xrefmap.yml", "testMoniker-1.1_justfortest.xrefmap.yml" }; var defaultXrefMap = xrefmaps.FirstOrDefault(x => string.Equals(x, DefaultXrefMap, StringComparison.OrdinalIgnoreCase)); var defaultVersionInfo = !string.IsNullOrEmpty(defaultXrefMap) ? new VersionInfo(string.Empty, defaultXrefMap) : null; var xrefmapsWithVersion = xrefmaps.Where(x => !string.IsNullOrEmpty(x) && x.EndsWith(XrefMapSuffix)); foreach (var xrefmapWithVersion in xrefmapsWithVersion) { var escapedVersion = xrefmapWithVersion.Substring(0, xrefmapWithVersion.Length - XrefMapSuffix.Length); if (!string.IsNullOrEmpty(escapedVersion)) { var unescapedversion = Uri.UnescapeDataString(escapedVersion); VersionInfo versionInfoItem; if (versionInfo.TryGetValue(unescapedversion, out versionInfoItem) && versionInfoItem != null) { versionInfoItem.XRefMap = xrefmapWithVersion; } } } var branch = "live"; myret(branch); Directory.CreateDirectory(@"c:\ab\c\text.txt"); //webc.Get(new Uri("c:\\ab.txt")); var da = new string[] { "1" }; var fir = da.First(x => x == "2"); foreach (var fi in fir) { Console.WriteLine(""); } Digit <string[]> dig = new Digit <string[]>(da); //This call invokes the implicit "double" operator string[] num = dig; //string snu = null; //var tsnu = (string)snu; //var t1 = PrintAsync(1); //var t2 = PrintAsync(2); //var t3 = PrintAsync(3); //var t4 = PrintAsync(4); //var t5 = PrintAsync(5); //var tasks = new List<Task> { t1, t2, t3 }; //TaskHelper.WhenAll(tasks, 2).Wait(); var depots = new List <string> { "1", "4", "2", "3" }; var allDepots = depots.Concat(new List <string> { "6" }); var dep = fff(depots).Result; var orderDepots = depots.OrderByDescending(depot => IsCurrentDepot("1", depot)); var nr = FileUtility.NormalizeRelativePath("test.txt"); var de = default(string); var manifestJson = File.ReadAllText(@"C:\Users\ychenu\Downloads\2929183a-17190aeb%5C201708210354455948-master\testMultipleVersion\test.json"); var buildManifest = JsonUtility.FromJsonString <BuildManifest>(manifestJson); foreach (var item in buildManifest.ItemsToPublish) { if (item.Type == PublishItemType.XrefMap) { Console.WriteLine($"{item.RelativePath} is xrefmap"); } } IEnumerable <string> itemss = new List <string> { "1.json", "2.json", "3.json" }; var itemsss = itemss.ToList(); itemss.GenerateMtaJsonFilesAsync().Wait(); var filename = Path.ChangeExtension("test\\test.md", ".mta.json"); JsonUtility.ToJsonFile(filename, "test"); var combined = Path.Combine("test\\index.md", ".mta.json"); var loop = TestLoop(3).ToList(); var version = "<abc>"; var escapedata = Uri.EscapeDataString(version); var data = Uri.UnescapeDataString(escapedata); Dictionary <string, List <string> > repoByKey = new Dictionary <string, List <string> >(); repoByKey["key1"] = new List <string> { "1" }; var repos = repoByKey["key1"]; repos.Add("2"); File.WriteAllLines(@"D:\Data\DataFix\FixLocRepoConfig\test.txt", new List <string> { "1", "2" }); File.AppendText(@"D:\Data\DataFix\FixLocRepoConfig\test.txt"); var now = $"{DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss")}.log"; var utcnow = DateTime.UtcNow.ToString("yyyyMMddHHmmss"); var pa = Path.Combine(@"c:\test\testfile", "RepositoryTableData.json"); var dir = Path.GetDirectoryName(@"c:\test\testfile\abc.txt"); Directory.CreateDirectory(dir); File.WriteAllText(@"c:\test\testfile\abc.txt", "test"); var list = new List <int> { }; var filter = list.Where(i => i == 3).ToList(); var useAsync = ConfigurationManager.AppSettings["UseAsync"]; var parallelism = -1; int.TryParse(ConfigurationManager.AppSettings["Parallelism"], out parallelism); Task.Factory.StartNew(() => { Thread.Sleep(5000); Console.WriteLine("sleep for 5s"); }).Wait(); var herf = "api/System.Web.UI.MobileControls.MobileListItem.OnBubbleEvent.html#System_Web_UI_MobileControls_MobileListItem_OnBubbleEvent_System_Object_System_EventArgs_"; var rep = GetNormalizedFileReference(herf, string.Empty); var dic = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase); dic.Add("a", 1); dic.Add("A", 40); dic.Add("context", new Dictionary <string, object> { { "1", 3 } }); var hash = Hash.FromDictionary(dic); Console.WriteLine("before WaitForSomething"); WaitForSomething(); Console.WriteLine("after WaitForSomething"); AsyncAwaitDemo.Get().Wait(); var ie = new string[] { }.Where(i => i == ""); var jjj = string.Join(",", null); try { using (var reader = new StreamReader(@"C:\TestFiles\log.json")) { string line; while ((line = reader.ReadLine()) != null) { var logItem = JsonUtility.FromJsonString <LogItem>(line); } } } catch (Exception ex) { Console.WriteLine(ex); } var directory = @"C:\Git\OpenPublishing.Build"; var extensions = new string[] { ".config", ".csproj" }; var oldVersion = "2.19.0-alpha-0681-g405ed2d"; var newVersion = "2.19.0"; UpdatePackageVersion.Update(directory, extensions, oldVersion, newVersion); Convert.ToBoolean("s"); bool result; if (bool.TryParse(null, out result)) { var ssss = result; } var sbtest = new StringBuilder(); testsb(sbtest); sbtest.AppendLine("out of testsb"); Console.WriteLine(sbtest.ToString()); var silent = false; try { throw new FileNotFoundException(""); } catch (Exception) when(silent) { Console.WriteLine("catch"); } var li = new List <int> { 1, 2 }; var second = new List <int> { 3, 2 }; var exc = li.Except(second); li.Add(1); li.Add(1); var permission = OpsPermission.ReadOnly; permission |= OpsPermission.MonikerAdmin; var re = new int[] { 1 }.Where(x => x == 3); var co = re.Count(); CancellationTokenSource cts = new CancellationTokenSource(); ParallelOptions po = new ParallelOptions(); po.CancellationToken = cts.Token; Task.Factory.StartNew(() => { if (Console.ReadKey().KeyChar == 'c') { cts.Cancel(); } Console.WriteLine("press any key to exit"); }); Parallel.ForEach(new List <int>(), po, (algo) => { Task.Delay(2000).Wait(); // this compute lasts 1 minute Console.WriteLine("this job is finished"); po.CancellationToken.ThrowIfCancellationRequested(); }); try { Task.Run(() => { for (var i = 0; i < 100; ++i) { throw new Exception("throw from run"); } }); } catch (AggregateException aex) { Console.WriteLine("aex"); } catch (Exception ex) { Console.WriteLine("ex"); } var exchangeSvc = new MsExchange.ExchangeService(MsExchange.ExchangeVersion.Exchange2010) { Url = new Uri("https://outlook.office365.com/ews/exchange.asmx"), Credentials = new MsExchange.WebCredentials("*****@*****.**", "#Bugsfor$-160802"), TraceEnabled = true }; var message = new MsExchange.EmailMessage(exchangeSvc); message.ToRecipients.Add("*****@*****.**"); message.Subject = "test"; message.Body = "test body"; message.Save(); message.Send(); CreateOrUpdateDocument("abc_id", 6, new CreateOrUpdateDocumentRequest { ContentSourceUri = null, Metadata = new Dictionary <string, object> { { "assetId", "s" }, { "d", 7 } } }); var name = $"{nameof(args)}.{nameof(args.Rank)}"; var ar = new int[] { 6, 7, 3 }; var sortAr = ar.OrderByDescending(x => x); try { var fo = $"{"a"}{null}"; var items = new List <Item> { new Item { Version = "v1", Url = "d" }, new Item { Version = "v1", Url = "b" }, new Item { Version = "v1", Url = "c" }, new Item { Version = "v2", Url = "f" }, new Item { Version = "v2", Url = "a" } }; var web = new HtmlWeb() { //PreRequest = request => //{ // // Make any changes to the request object that will be used. // request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip; // return true; //} }; var document = web.Load(@"https://opdhsblobsandbox01.blob.core.windows.net/contents/0ced3babc6274b949a9696c03ed9d944/3094b7719e20479798997b70294c9ee3"); FolderUtility.ForceDeleteAllSubDirectories(@"C:\TestFiles\Test", 1); } catch (AggregateException aex) { Console.WriteLine("aex"); } catch (Exception ex) { Console.WriteLine("ex"); } var array = new Task[] { }; var f = array.FirstOrDefault(); Array.ForEach(array, ele => { Console.WriteLine(ele); }); var commentSb = new StringBuilder(); for (int j = 0; j < 2; j++) { commentSb.AppendFormat(" [View]({0})", "path" + j); commentSb.Append("<br/>"); } commentSb.Length -= "<br/>".Length; commentSb.AppendLine(@" File | Status | Preview URL | Details ---- | ------ | ----------- | -------"); for (int i = 0; i < 2; i++) { commentSb.AppendFormat( "[{0}]({1}) | {2} |", "path" + i, "http://abc" + i, "success"); var sb = new StringBuilder(); for (int j = 0; j < 2; j++) { commentSb.AppendFormat(" [View]({0})", "path" + j); if (j == 0) { commentSb.AppendFormat("({0})", j); } commentSb.Append("<br/>"); } commentSb.AppendFormat(" |"); commentSb.AppendFormat(" [Details](#user-content-{0})", "details"); commentSb.AppendLine(); } var strsb = commentSb.ToString(); File.WriteAllText(@"C:\TestFiles\comment.md", strsb); //var derived = new DerivedPackageDownloadAndUnzipPathInfo(); string source = null; Console.WriteLine($"{source}-abc"); var packageTypeToPathsMap = new Dictionary <BlobPackageType, PackageDownloadAndUnzipPathInfo>(); var skipPackageDownloadingMap = new Dictionary <BlobPackageType, bool>(); skipPackageDownloadingMap[BlobPackageType.Source] = true; skipPackageDownloadingMap[BlobPackageType.Cache] = true; var skip = JsonUtility.ToJsonString(skipPackageDownloadingMap); var packageTypeToSkipFlagMap = JsonUtility.FromJsonString <Dictionary <BlobPackageType, bool> >(skip); foreach (var packageTypeToSkipFlagKeyValuePair in packageTypeToSkipFlagMap) { var blobPackageType = packageTypeToSkipFlagKeyValuePair.Key; var skipPackageDownloading = packageTypeToSkipFlagKeyValuePair.Value; //if (!skipPackageDownloading) { var packageBlobDownloadPath = packageTypeToPathsMap[blobPackageType].PackageBlobDownloadPath; } } var path = Path.GetTempPath(); try { var details = "data ex"; throw new InvalidDataException($"invalid {details}"); } catch (InvalidDataException idex) { Console.WriteLine($"data ex: {idex}"); } catch (Exception ex) { Console.WriteLine("ex"); } var workingDirectory = Path.Combine(@"c:\users\ychenu", Path.GetRandomFileName().Substring(0, 4)); var work = new Work(); }
static void Main(string[] args) { #if AsyncAwaitTest AsyncAwaitDemo ins = new AsyncAwaitDemo(); ins.mainThreadFunc1_callLongRunTask_MainThreadWillNotBlockAtThisFunc(); ins.mainThreaddFunc2_WillNotBlockByFunc1(); ins.callMethod(); #endif #if Expression_DEMO ExpressionDemo ins = new ExpressionDemo(); ins.createExpression(); #endif #if TASK_THREAD_DEMO ThreadTaskDemo ins = new ThreadTaskDemo(); ins.createTask(); #endif #if LINQTOSQL LINQToSQL ins = new LINQToSQL(); ins.exer2(); #endif #if LINQTOXML LINQToXMLDemo ins = new LINQToXMLDemo(); ins.orderXML(); //ins.createTPDefaultRecipeXML(); //uint index; //List<string> options = new List<string>(); //ins.test("MEAS_TYPE", out index, out options); //Console.WriteLine("index: {0}", index); //foreach (var item in options) //{ // Console.WriteLine(item); //} #endif #if LINQStudy var nums = new int[7] { 0, 1, 2, 3, 4, 5, 6 }; var numQuery = from num in nums where (num % 2) == 0 select num; foreach (var num in numQuery) { Console.WriteLine("{0}", num); } #elif ReflectionTest Rectangle r = new Rectangle(4.5, 7.5); r.display(); Type type = typeof(Rectangle); //遍历类特性 foreach (object attributes in type.GetCustomAttributes(false)) { Debuginfo dbi = (Debuginfo)attributes; if (null != dbi) { Console.Write("Bug no: {0}\t", dbi.BugNo); Console.Write("Developer: {0}\t", dbi.Developer); Console.Write("Last Reviewed: {0}\t", dbi.LastReview); Console.Write("Remarks: {0}\t", dbi.Message); } Console.WriteLine(); } //遍历方法特性 foreach (MethodInfo method in type.GetMethods()) { foreach (Attribute a in method.GetCustomAttributes(true)) { Debuginfo dbi = (Debuginfo)a; if (null != dbi) { Console.Write("Bug no: {0}, for Method: {1} \t", dbi.BugNo, method.Name); Console.Write("Developer: {0}\t", dbi.Developer); Console.Write("Last Reviewed: {0}\t", dbi.LastReview); Console.Write("Remarks: {0}\t", dbi.Message); } } } #elif AttributeTest ToolKit.FuncA(); ToolKit.FuncB(); ToolKit.FuncC(); ToolKit.FuncD(); Console.ReadKey(); #elif IndexTest IndexerStudy names = new IndexerStudy(); names[0] = "wang"; names[1] = "ji"; names[2] = "chen"; for (int i = 0; i < IndexerStudy.size; i++) { Console.WriteLine(names[i]); } #elif DelegateAndEvent DelegateAndEventStudyPublisher publisher = new DelegateAndEventStudyPublisher(); Subscriber scriber = new Subscriber(); /***** !!! *****/ publisher.ChangeNum += new DelegateAndEventStudyPublisher.NumManipulationHandler(scriber.printf); /***** !!! *****/ publisher.SetVal(7); publisher.SetVal(11); #elif AnonymousFunction x => x + 1; x => { return(x + 1); } #endif Console.ReadKey(); }