I try to wait for the class to be finished with instantiate.
My architecture is the following. Cook is inheriade from CookChief.
And if I instantiate cook, CookChief is creating himself, but CookChief is calling 1 other class named Cookhelper the cookhelper is waiting for a input and for this input method i want to wait in Cook.
The thing is iam creating this in MVVM Galasoft and my entry point is the CookViewmodel, with a relaycommand.
In the code below you can see my architecture. To say it short I want to wait until this bool processed = await Task.Run(() => ValidateForDeviceId()); is finished.
My first step was to outsource the constructer of each class. And create a init method.
This is my code:
public CookViewModel()
{
startCookButtonCommand = new RelayCommand(Cook);
}
private async Task Cook()
{
cook.Init();
}
public class Cook : CookChief
{
public Cook()
{
}
public async Task Init()
{
await this.CookChiefInit();
//here I want to wait until CookChiefInit is finished
Cooking();
}
public void Cooking()
{
MessageBox.Show("Input received");
}
}
Now the Cookchief:
public Cookchief()
{
}
protected async Task CookchiefInit()
{
this.Cookhelper = new Cookhelper();
Cookhelper.CookHelperInit();
}
And in the CookHelper we do this:
public CookHelper()
{
}
public void CookHelperInit()
{
this.driverWindow = new DriverWindow();
startProc();
}
private async void startProc()
{
ShowOrCloseDriverWindow(true);
//this is the task what we wait for before we can repeat
bool processed = await Task.Run(() => ValidateForDeviceId());
if(processed)
{
ShowOrCloseDriverWindow(false);
}
else
{
MessageBox.Show("DriverError");
}
}
private bool ValidateForDeviceId()
{
for (; ; )
{
this.deviceId = Input.deviceId;
if (deviceId > 0)
{
break;
}
}
return true;
}
Per the discussion in the comments, the problem here was that the initialization routine mixed synchronous and asynchronous methods and calls. Additionally, some async methods were called without the await keyword. The solution was to make all calls asynchronous and await them.
cook.Init() needs an await:
private async Task Cook()
{
await cook.Init();
}
In CookchiefInit(), the CookHelperInit() call needs to be awaited:
protected async Task CookchiefInit()
{
this.Cookhelper = new Cookhelper();
Cookhelper.CookHelperInit();
}
In order to await CookHelperInit(), it needs to be made asynchronous. The startProc() call is to an async method, so it must also be awaited:
public async Task CookHelperInit()
{
this.driverWindow = new DriverWindow();
await startProc();
}
Many of the tutorials I've read on async/await feel like they complicate the concept way too much. Ideally, it would allow some time consuming task to be run in the background while the calling method continues its business.
I decided to create the simplest example of async/await I can think of. C# console application:
class Program
{
static void Main(string[] args)
{
PrintTwoTimes();
Console.WriteLine("Main Method!");
Console.ReadLine();
}
async static Task PrintTwoTimes()
{
await Task.Run(() =>
{
Thread.Sleep(500);
Console.WriteLine("Inside Async Task!");
});
Console.WriteLine("After Async Task!");
}
}
The output is as I expected.
The calling thread continues its execution without waiting for PrintTwoTimes() to complete.
What I'd like to know is what is dangerous about such a simple approach to async/await, as I have done, in the real world?
* EDIT *
After being told my question is idiotic, I am removing the bit about static and adding updated code that removes it
class Program
{
static void Main(string[] args)
{
//call the async thread
var prtclss = new PrintClass();
prtclss.PrintTwoTimes();
Console.WriteLine("Main Method!");
Console.ReadLine();
}
}
class PrintClass
{
public string str1 { get; set; }
public string str2 { get; set; }
public PrintClass()
{
str1 = "Inside Async Task!";
str2 = "After Async Task!";
}
public async Task PrintTwoTimes()
{
await Task.Run(() =>
{
//simulate time consuming task
Thread.Sleep(500);
Console.WriteLine(str1);
});
Console.WriteLine(str2);
}
}
Summary: I would like to call an asynchronous method in a constructor. Is this possible?
Details: I have a method called getwritings() that parses JSON data. Everything works fine if I just call getwritings() in an async method and put await to left of it. However , when I create a LongListView in my page and try to populate it I'm finding that getWritings() is surprisingly returning null and the LongListView is empty.
To address this problem, I tried changing the return type of getWritings() to Task<List<Writing>> and then retrieving the result in the constructor via getWritings().Result. However, doing that ends up blocking the UI thread.
public partial class Page2 : PhoneApplicationPage
{
List<Writing> writings;
public Page2()
{
InitializeComponent();
getWritings();
}
private async void getWritings()
{
string jsonData = await JsonDataManager.GetJsonAsync("1");
JObject obj = JObject.Parse(jsonData);
JArray array = (JArray)obj["posts"];
for (int i = 0; i < array.Count; i++)
{
Writing writing = new Writing();
writing.content = JsonDataManager.JsonParse(array, i, "content");
writing.date = JsonDataManager.JsonParse(array, i, "date");
writing.image = JsonDataManager.JsonParse(array, i, "url");
writing.summary = JsonDataManager.JsonParse(array, i, "excerpt");
writing.title = JsonDataManager.JsonParse(array, i, "title");
writings.Add(writing);
}
myLongList.ItemsSource = writings;
}
}
The best solution is to acknowledge the asynchronous nature of the download and design for it.
In other words, decide what your application should look like while the data is downloading. Have the page constructor set up that view, and start the download. When the download completes update the page to display the data.
I have a blog post on asynchronous constructors that you may find useful. Also, some MSDN articles; one on asynchronous data-binding (if you're using MVVM) and another on asynchronous best practices (i.e., you should avoid async void).
You can also do just like this:
Task.Run(() => this.FunctionAsync()).Wait();
Note: Be careful about thread blocking!
I'd like to share a pattern that I've been using to solve these kinds of problems. It works rather well I think. Of course, it only works if you have control over what calls the constructor.
public class MyClass
{
public static async Task<MyClass> Create()
{
var myClass = new MyClass();
await myClass.Initialize();
return myClass;
}
private MyClass()
{
}
private async Task Initialize()
{
await Task.Delay(1000); // Do whatever asynchronous work you need to do
}
}
Basically what we do is we make the constructor private and make our own public static async method that is responsible for creating an instance of MyClass. By making the constructor private and keeping the static method within the same class we have made sure that no one could "accidentally" create an instance of this class without calling the proper initialization methods.
All the logic around the creation of the object is still contained within the class (just within a static method).
var myClass1 = new MyClass() // Cannot be done, the constructor is private
var myClass2 = MyClass.Create() // Returns a Task that promises an instance of MyClass once it's finished
var myClass3 = await MyClass.Create() // asynchronously creates and initializes an instance of MyClass
Implemented on the current scenario it would look something like:
public partial class Page2 : PhoneApplicationPage
{
public static async Task<Page2> Create()
{
var page = new Page2();
await page.getWritings();
return page;
}
List<Writing> writings;
private Page2()
{
InitializeComponent();
}
private async Task getWritings()
{
string jsonData = await JsonDataManager.GetJsonAsync("1");
JObject obj = JObject.Parse(jsonData);
JArray array = (JArray)obj["posts"];
for (int i = 0; i < array.Count; i++)
{
Writing writing = new Writing();
writing.content = JsonDataManager.JsonParse(array, i, "content");
writing.date = JsonDataManager.JsonParse(array, i, "date");
writing.image = JsonDataManager.JsonParse(array, i, "url");
writing.summary = JsonDataManager.JsonParse(array, i, "excerpt");
writing.title = JsonDataManager.JsonParse(array, i, "title");
writings.Add(writing);
}
myLongList.ItemsSource = writings;
}
}
Instead of doing
var page = new Page2();
you would be using:
var page = await Page2.Create();
A quick way to execute some time-consuming operation in any constructor is by creating an action and run them asynchronously.
new Action( async() => await InitializeThingsAsync())();
Running this piece of code will neither block your UI nor leave you with any loose threads. And if you need to update any UI (considering you are not using MVVM approach), you can use the Dispatcher to do so as many have suggested.
A Note: This option only provides you a way to start an execution of a method from the constructor if you don't have any init or onload or navigated overrides. Most likely this will keep on running even after the construction has been completed. Hence the result of this method call may NOT be available in the constructor itself.
My preferred approach:
// caution: fire and forget
Task.Run(async () => await someAsyncFunc());
Try to replace this:
myLongList.ItemsSource = writings;
with this
Dispatcher.BeginInvoke(() => myLongList.ItemsSource = writings);
To put it simply, referring to Stephen Cleary https://stackoverflow.com/a/23051370/267000
your page on creation should create tasks in constructor and you should declare those tasks as class members or put it in your task pool.
Your data are fetched during these tasks, but these tasks should awaited in the code i.e. on some UI manipulations, i.e. Ok Click etc.
I developped such apps in WP, we had a whole bunch of tasks created on start.
You could try AsyncMVVM.
Page2.xaml:
<PhoneApplicationPage x:Class="Page2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<ListView ItemsSource="{Binding Writings}" />
</PhoneApplicationPage>
Page2.xaml.cs:
public partial class Page2
{
InitializeComponent();
DataContext = new ViewModel2();
}
ViewModel2.cs:
public class ViewModel2: AsyncBindableBase
{
public IEnumerable<Writing> Writings
{
get { return Property.Get(GetWritingsAsync); }
}
private async Task<IEnumerable<Writing>> GetWritingsAsync()
{
string jsonData = await JsonDataManager.GetJsonAsync("1");
JObject obj = JObject.Parse(jsonData);
JArray array = (JArray)obj["posts"];
for (int i = 0; i < array.Count; i++)
{
Writing writing = new Writing();
writing.content = JsonDataManager.JsonParse(array, i, "content");
writing.date = JsonDataManager.JsonParse(array, i, "date");
writing.image = JsonDataManager.JsonParse(array, i, "url");
writing.summary = JsonDataManager.JsonParse(array, i, "excerpt");
writing.title = JsonDataManager.JsonParse(array, i, "title");
yield return writing;
}
}
}
Don't ever call .Wait() or .Result as this is going to lock your app.
Don't spin up a new Task either, just call the ContinueWith
public class myClass
{
public myClass
{
GetMessageAsync.ContinueWith(GetResultAsync);
}
async Task<string> GetMessageAsync()
{
return await Service.GetMessageFromAPI();
}
private async Task GetResultAsync(Task<string> resultTask)
{
if (resultTask.IsFaulted)
{
Log(resultTask.Exception);
}
eles
{
//do what ever you need from the result
}
}
}
https://learn.microsoft.com/en-us/dotnet/standard/asynchronous-programming-patterns/consuming-the-task-based-asynchronous-pattern
A little late to the party, but I think many are struggling with this...
I've been searching for this as well. And to get your method/action running async without waiting or blocking the thread, you'll need to queue it via the SynchronizationContext, so I came up with this solution:
I've made a helper-class for it.
public static class ASyncHelper
{
public static void RunAsync(Func<Task> func)
{
var context = SynchronizationContext.Current;
// you don't want to run it on a threadpool. So if it is null,
// you're not on a UI thread.
if (context == null)
throw new NotSupportedException(
"The current thread doesn't have a SynchronizationContext");
// post an Action as async and await the function in it.
context.Post(new SendOrPostCallback(async state => await func()), null);
}
public static void RunAsync<T>(Func<T, Task> func, T argument)
{
var context = SynchronizationContext.Current;
// you don't want to run it on a threadpool. So if it is null,
// you're not on a UI thread.
if (context == null)
throw new NotSupportedException(
"The current thread doesn't have a SynchronizationContext");
// post an Action as async and await the function in it.
context.Post(new SendOrPostCallback(async state => await func((T)state)), argument);
}
}
Usage/Example:
public partial class Form1 : Form
{
private async Task Initialize()
{
// replace code here...
await Task.Delay(1000);
}
private async Task Run(string myString)
{
// replace code here...
await Task.Delay(1000);
}
public Form1()
{
InitializeComponent();
// you don't have to await nothing.. (the thread must be running)
ASyncHelper.RunAsync(Initialize);
ASyncHelper.RunAsync(Run, "test");
// In your case
ASyncHelper.RunAsync(getWritings);
}
}
This works for Windows.Forms and WPF
In order to use async within the constructor and ensure the data is available when you instantiate the class, you can use this simple pattern:
class FooClass : IFooAsync
{
FooClass
{
this.FooAsync = InitFooTask();
}
public Task FooAsync { get; }
private async Task InitFooTask()
{
await Task.Delay(5000);
}
}
The interface:
public interface IFooAsync
{
Task FooAsync { get; }
}
The usage:
FooClass foo = new FooClass();
if (foo is IFooAsync)
await foo.FooAsync;
Brian Lagunas has shown a solution that I really like. More info his youtube video
Solution:
Add a TaskExtensions method
public static class TaskExtensions
{
public static async void Await(this Task task, Action completedCallback = null ,Action<Exception> errorCallBack = null )
{
try
{
await task;
completedCallback?.Invoke();
}
catch (Exception e)
{
errorCallBack?.Invoke(e);
}
}
}
Usage:
public class MyClass
{
public MyClass()
{
DoSomething().Await();
// DoSomething().Await(Completed, HandleError);
}
async Task DoSomething()
{
await Task.Delay(3000);
//Some works here
//throw new Exception("Thrown in task");
}
private void Completed()
{
//some thing;
}
private void HandleError(Exception ex)
{
//handle error
}
}
The answer is simple, If you are developing an UWP app, then add the async function to the Page_Loaded method of the page.
if you want it to wait task to be done you can improve madlars codes like below. (I tried on .net core 3.1 it worked )
var taskVar = Task.Run(async () => await someAsyncFunc());
taskVar.Wait();
You could put the async calls in a separate method and call that method in the constructor.
Although, this may lead to a situation where some variable values not being available at the time you expect them.
public NewTravelPageVM(){
GetVenues();
}
async void GetVenues(){
var locator = CrossGeolocator.Current;
var position = await locator.GetPositionAsync();
Venues = await Venue.GetVenues(position.Latitude, position.Longitude);
}
I have a silverlight application which is making multiple async calls:
The problem I am facing is to how to determine if all the async calls are finished so that I can stop displaying the progress indicator. In the example below, progress indicator is stopped as soon as the first async method returns.
Any tips on how to resolve this ?
Constructor()
{
startprogressindicator();
callasync1(finished1);
callasync2(finished2);
//.... and so on
}
public void finished1()
{
stopprogressindicator();
}
public void finished2()
{
stopprogressindicator();
}
You need to asynchronously wait for both methods to finish, currently you call stopprogressindicator as soon as any of the method completes.
Refactor your code to return Task from callasync1 and callasync2 Then you can do
var task1 = callasync1();
var task2 = callasync2();
Task.Factory.ContinueWhenAll(new []{task1, task2}, (antecedents) => stopprogressindicator());
I do like the idea of using Task API, but in this case you may simply use a counter:
int _asyncCalls = 0;
Constructor()
{
startprogressindicator();
Interlocked.Increment(ref _asyncCalls);
try
{
// better yet, do Interlocked.Increment(ref _asyncCalls) inside
// each callasyncN
Interlocked.Increment(ref _asyncCalls);
callasync1(finished1);
Interlocked.Increment(ref _asyncCalls);
callasync2(finished2);
//.... and so on
}
finally
{
checkStopProgreessIndicator();
}
}
public checkStopProgreessIndicator()
{
if (Interlocked.Decrement(ref _asyncCalls) == 0)
stopprogressindicator();
}
public void finished1()
{
checkStopProgreessIndicator()
}
public void finished2()
{
checkStopProgreessIndicator()
}
I'm working on an MVC application, that uses some Windows Workflow behind the scenes for automation.
I have implemented some code to wait for the Workflow to complete. below is a sample app that boils down the problem to its key parts.
The issue doesn't really have to do with the work going on in the WF activity, but more how I'm waiting for it to complete.
HomeController.cs
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult ProcessRequest()
{
int[] arr = new int[0];
var wh = new ManualResetEvent(false);
var instance = new Activities.SampleCodeActivity();
var args = new Dictionary<string, object>();
args.Add("Limit", 25);
var app = new WorkflowApplication(instance, args);
app.Completed = resultArgs =>
{
var list = (List<int>)resultArgs.Outputs["Primes"];
arr = list.ToArray();
wh.Set();
};
app.Run();
wh.WaitOne();
return Json(arr);
}
Index.cshtml
#{ ViewBag.Title = "Index"; }
<script src="../../Scripts/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
var tools = {};
tools.processRequest = function () {
$.ajax({
url: "#Url.Action("ProcessRequest")", type: "POST",
success: function (data) {
alert(data);
}
});
};
$(document).ready(function () {
tools.processRequest();
});
</script>
<h2>Index</h2>
SampleCodeActivity.cs
public class SampleCodeActivity : CodeActivity
{
public InArgument<int> Limit { get; set; }
public OutArgument<List<int>> Primes { get; set; }
private List<int> _list = new List<int>();
protected override void Execute(CodeActivityContext context)
{
var limit = context.GetValue(Limit);
checkForPrimes(limit);
context.SetValue(Primes, _list);
}
private void checkForPrimes(int limit)
{
for (var x = 2; x <= limit; x++)
if (isPrime(x)) _list.Add(x);
}
private bool isPrime(int value)
{
for (var x = value - 1; x > 1; x--)
if (value % x == 0) return false;
return true;
}
}
My question is regarding the WaitHandle/ManualResetEvent in the Controller Action. Is there a better way to implement this using Tasks, etc? I am using .NET 4.5.
Without the WaitHandle in place the Action returns before the workflow has completed.
I am familiar with WaitHandle, but it feels like a klunky solution.
Any help / guidance is appreciated.
WaitHandle is an abstract class providing the ability to wait for access to shared resources at the operating system level. If you wish to synchronize access at this level, there is no getting away from using it. However, as you mention, using something like the ManualResetEvent can interrupt the flow of your code, making it hard to read and diagnose when things go wrong.
Many of the recent additions to the .NET framework regarding threading attempt to address this issue. In .NET 4 the notion of Task was introduced, which can streamline the code somewhat, and C# 5 built on top of that infrastructure to introduce the async/await keywords. The code below is a simple console application, showing three ways of achieving what you want using ManualResetEvent, Task's and async/await.
It is important to realize that all three are using the WaitHandle class at some level to synchronize the threads, but the readability is improved using Task's and async/await.
class Program
{
static void Main(string[] args)
{
List<int> results;
//Using raw Wait Handle
ManualResetEvent handle = new ManualResetEvent(false);
Thread thread = new Thread(o =>
{
//Long running process
results = LongRunningTask();
handle.Set();
});
thread.Start();
handle.WaitOne();
Console.WriteLine("Thread completed");
//Using Tasks
Task<List<int>> task = Task<List<int>>.Factory.StartNew(LongRunningTask);
results = task.Result;
Console.WriteLine("Task completed");
//Using async/await
results = LongRunningTaskAsync().Result;
Console.WriteLine("Async Method completed");
Console.ReadLine();
}
public static List<int> LongRunningTask()
{
Thread.Sleep(5000);
return new List<int>();
}
public static async Task<List<int>> LongRunningTaskAsync()
{
return await Task<List<int>>.Factory.StartNew(LongRunningTask);
}
}