Bug 15072 - Console.WriteLine shows no text from a Task.Run unless you Console.Writeline from main thread first.
Summary: Console.WriteLine shows no text from a Task.Run unless you Console.Writeline ...
Status: RESOLVED INVALID
Alias: None
Product: Class Libraries
Classification: Mono
Component: System ()
Version: 3.2.x
Hardware: Macintosh Mac OS
: --- normal
Target Milestone: Untriaged
Assignee: Bugzilla
URL:
Depends on:
Blocks:
 
Reported: 2013-09-30 13:51 UTC by Eric Hosick
Modified: 2013-09-30 14:12 UTC (History)
1 user (show)

Tags:
Is this bug a regression?: ---
Last known good build:

Notice (2018-05-24): bugzilla.xamarin.com is now in read-only mode.

Please join us on Visual Studio Developer Community and in the Xamarin and Mono organizations on GitHub to continue tracking issues. Bugzilla will remain available for reference in read-only mode. We will continue to work on open Bugzilla bugs, copy them to the new locations as needed for follow-up, and add the new items under Related Links.

Our sincere thanks to everyone who has contributed on this bug tracker over the years. Thanks also for your understanding as we make these adjustments and improvements for the future.


Please create a new report on GitHub or Developer Community with your current version information, steps to reproduce, and relevant error messages or log files if you are hitting an issue that looks similar to this resolved bug and you do not yet see a matching new report.

Related Links:
Status:
RESOLVED INVALID

Description Eric Hosick 2013-09-30 13:51:27 UTC
Following code causes the problem.

When writeOutsideOfThread is false, no text is shown in console. When true, we see text in console.


using System;
using System.Threading.Tasks;

namespace runAsyncTest
{
	class MainClass
	{

		public static void TaskMethodSynchronous() {
			Console.WriteLine ("In TaskMethodSynchronous");
		}

		/// <summary>
		/// Runs the TaskMethodSynchronous asynchronously. A method wrapper because Task.Run can not use properties
		/// </summary>
		public static async void TaskMethodAsync() {
			await Task.Run (() => TaskMethodSynchronous());
		}


		public static void Main (string[] args) {
			bool writeOutsideOfThread = false; // When false, nothing is written.

			if (writeOutsideOfThread) {
				Console.WriteLine ("We only see text written to console from a task if we write text from main thread first.");
			}
			TaskMethodAsync();
		}
	}
}
Comment 1 Mikayla Hutchinson [MSFT] 2013-09-30 13:57:29 UTC
Your program is exiting before TaskMethodSynchronous() runs. Basically, it's a race.

You should make TaskMethodAsync return Task, and then TaskMethodAsync().Wait(); to ensure your program waits for the task to finish before it exits.
Comment 2 Eric Hosick 2013-09-30 14:12:19 UTC
Thanks for such a quick response. I should have realized that.