Trying to make method wait for internal event handling finished - c#

I'm new in C# async/await and facing some issues while trying to work with async method.
I have a collection:
private IList<IContactInfo> _contactInfoList
And an async method:
public async Task<IList<IContactInfo>> SelectContacts()
{
_contactInfoList = new List<IContactInfo>();
ContactsSelector selector = new ContactsSelector();
selector.ShowPicker();
selector.ContactsSelected += (object sender, ContactsSelectorEventArgs e) =>
{
this._contactInfoList = e.Contacts;
};
return _contactInfoList;
}
Contact selector is a popup user control which allows to select some contacts from phone and after the "OK" button tapped it fires ContactsSelected event. I need to get the selected contacts list from the event arguments e.Contacts and return that list in above mentioned SelectContacts() async method. And here is the issue: My method is already returning empty list _contactInfoList before the ContactsSelected event has finished his job. I know that async/await even doesn't matter in this case and this issue will be exist in usual method, but I just need to make that method to wait event handling result.

What you need to do here is convert an event style of asynchronous programming to a task style of asynchronous programming. The use of a TaskCompletionSource make this fairly straightforward.
public static Task<IList<IContactInfo>> WhenContactsSelected(
this ContactsSelector selector)
{
var tcs = new TaskCompletionSource<IList<IContactInfo>>();
selector.ContactsSelected += (object sender, ContactsSelectorEventArgs e) =>
{
tcs.TrySetResult(e.Contacts);
};
return tcs.Task;
}
Now that we have a method that returns a task with the result that we need, the method that uses it is quite straightforward:
public Task<IList<IContactInfo>> SelectContacts()
{
ContactsSelector selector = new ContactsSelector();
selector.ShowPicker();
return selector.WhenContactsSelected();
}
There are a few things to note here. First, I removed the instance field; that seems like a bad idea here. If SelectContacts is called several times it would result in the two fighting over that field. Logically if you do need to store the list it should be a local variable. Next, there are no await uses here, so the method shouldn't be marked as async. If you wanted to await the call to WhenContactsSelected then feel free to add async back in, but as of now I see no real need for it.

Related

Calling functions one after other in event driven programming

I'm working on a software where software issues commands for hardware panel and once a command is issued, its response received after few seconds . there are different functions for different hardware commands like
public void FunctionA()
{
StartCommandA();
}
and other functions on the same pattern that will be used to run other commands.
FunctionB();
FunctionC();
Once we receive the response of command A , I invoke the other function from the response but this approach is not good as per design pattern practices.
All i want to do is to make a list of functions and invoke all these functions one after other, But next function will be called once i get response of first functions.
I tried this by using Multicast delegate but I'm unable to find out how we can call get the list of functions once i add all functions to that delegates. This is what i'm trying do since.
FunList funList_ConfigAndSerialTests = new FunList(StartSerialTest);
funList_ConfigAndSerialTests += StartSerialTest;
funList_ConfigAndSerialTests += StartMsrTest;
funList_ConfigAndSerialTests += StartContactLessTest;
//funList_ConfigAndSerialTests.Invoke();
Delegate[] del = funList_ConfigAndSerialTests.GetInvocationList();
foreach (Delegate item in funList_ConfigAndSerialTests.GetInvocationList())
{
while (true)
{
if (IsResponseReceived == true)
{
// Call function here
}
}
}
The simplest way to do this is to call the functions one by one:
FunctionA();
FunctionB();
FunctionC();
Each method will be called only after the previous has returned.
But you said you want to call the next function after the previous one has a response. Now that sounds like your functions run asynchronously. I strongly suggest you use the async keyword to mark your functions and make them return a Task<ResonseType>. You can learn about this here.
You'll then be able to do something like this:
await FunctionA(); // you obviously want to do something with the returned response
// I do not know your requirements so I did not show that part
await FunctionB();
await FunctionC();
It seems what you're trying to achieve is what Events are for. In the class, where the handlers (FunctionA, FunctionB, ...) are defined create an event instance as follows:
public class MyClass
{
private event Action Event;
public void RegisterHandlers()
{
Event += FuncA;
Event += FuncB;
Event();
}
public void HandleCommand()
{
this.Event();
}
private void FuncA() { /*...*/ }
private void FuncB() { /*...*/ }
}
The simple call to Events() will actually result in all the registered handlers to be invoked in the order they've been registered.

uwp C# cancel async task and re-run

Thanks in advance.
I want to use a foreach to add items to a `GridView . This is done in an async method.
I want to retrieve the items from other async methods and display them in a GridView:
public async Task SetGridItems(CancellationToken ct, /* and some items */)
{
GridItems.clear();
//get two list of item I want
var ListA = await getBmethodAsync().AsTask(ct);
var ListB = await getAmethodAsync().AsTask(ct);
foreach (itemA A in ListA)
{
GridItem i = new GridItem();
//set name
i.name = A.Name;
//get icon
i.image = img;
GridItems.Add(i);
}
foreach (ItemB b in ListB)
{
GridItem i = new GridItem();
i.name = b.Name;
i.image.SetSource(icon);
GridItems.Add(i);
}
}
The content is simplified for convenience.
When I run this method in a button click handler:
private async void check_btn2_Click(object sender, RoutedEventArgs e)
{
if (cts != null) {
cts.Cancel();
debug.Text = "cancel a job 4";
}
cts = new CancellationTokenSource();
try
{
await SetGridItems(ct.Token, /* and some items */).AsAsyncAction().AsTask(cts.Token);
}
catch (OperationCanceledException) { debug.Text = "cancel a job"; }
}
Here is the problem:
If I click this button twice (clicking fast):
- on the first click, the event callback will be called and my task will start to run
- something will show in the GridView but will not complete (it ends at 80%)
- on second click, the GridView is cleared as expected, and some new content is loaded but the GriViewis only showing the last 20% of the first click task
So, why does the second click not cancelling the first task ?
I've searched for a long time on net, nut haven't found anything. Please help and try to give some ideas how to achieve this.
I am not good at English and thanks
I see two problems here:
First as Vincent said in the comment, you're passing the cancellation token in a little redundant way with the AsAsyncAction().AsTask(cts.Token); in the button click handler and the .AsTask(ct); in the method itself.
Second, and much more important, you're passing the cancellation token to the task, but you're never using it in the method. Passing a cancellation token to a task is mostly used in parallel, not async work. It's a way for you to coordinate and query the execution state of multiple tasks running at once. And anyway, its always dependent on the usage of the token itself inside the executing code. Think of it this way, you're telling the task object itself that you're cancelling the operation, but your code doesn't know how to handle it.
In async development, you don't really need to pass the cancellation to the task object, since you don't have to coordinate the state of many of them, you're only executing the one. You should pass the token to your method, and let your code handle it.
So inside your SetGridItems method, try doing something like this:
public async Task SetGridItems(CancellationToken ct, /* and some items */)
{
GridItems.clear();
//get two list of item I want
var ListA = await getBmethodAsync().AsTask(ct);
var ListB = await getAmethodAsync().AsTask(ct);
foreach (itemA A in ListA)
{
ct.ThrowIfCancellationRequested();
GridItem i = new GridItem();
//set name
i.name = A.Name;
//get icon
i.image = img;
GridItems.Add(i);
}
foreach (ItemB b in ListB)
{
ct.ThrowIfCancellationRequested();
GridItem i = new GridItem();
i.name = b.Name;
i.image.SetSource(icon);
GridItems.Add(i);
}
}
Make sure to do the same in the GetXMethodAsync methods. This way your code knows how to handle the cancellation. Because right now, the task object may be cancelled, but it still keeps executing the code, since it doesn't know where to stop.
For more on task cancellation you can see the following links:
1. https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/task-cancellation
2. https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/how-to-cancel-a-task-and-its-children
Hope this helps

How to update TextBlock when async HttpRequest is finished?

I'm working on an app and I'm restructuring my code.
On my MainPage.xaml.cs I have a TextBlock and a ListBox. I have separate file (Info.cs) that handles the HttpRequest to get the information that I need to load.
The HttpRequest in Info.cs gets information from a weather API. When it gets all the information it puts the info in a ObservableCollection.. This ObservableCollection is bind to the ListBox.
Now, I'd like to update the TextBlock when the HttpRequest is finished, to show the user that all the information has been loaded.
How can I achieve this?
MainPage.xaml.cs:
WeatherInfo weatherInfo = new WeatherInfo();
weatherInfo.getTheWeatherData();
DataContext = weatherInfo;
WeatherListBox.ItemsSource = weatherInfo.ForecastList;
StatusTextBlock.Text = "Done.";
In the Info.cs I have a Dispatcher to fill the ForecastList:
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
ForecastList.Clear();
ForecastList = outputList;
}
What happens now is that the TextBlock instantly changes to "Done!" (doh, its Async!) but how can I change this? So it 'waits' on the ListBox to be updated? Unfortunatly there is no 'ItemsSourceChanged' event in Windows Phone.
I suggest to use the new async+await power from C# 5.0, This is actually a good practice to use async programming in WP8.
assuming you have control of getTheWeatherData() method, and that you can mark it as async method that returns Task, you will be able to call it using await modifier.
await will not block the UI, and will cause the next code lines to be executed only after the task is done.
WeatherInfo weatherInfo = new WeatherInfo();
await weatherInfo.getTheWeatherData();
DataContext = weatherInfo;
WeatherListBox.ItemsSource = weatherInfo.ForecastList;
StatusTextBlock.Text = "Done.";
Edit:
It is supported on WP 8, and on WP 7.5 through Microsoft.Bcl.Async Nuget Package
If async programming is not an option,
you can always create a callback event in WeatherInfo class that will be signaled inside getTheWeatherData(), and register to it on the UI.
One option looks as follows:
public static void DoWork(Action processAction)
{
// do work
if (processAction != null)
processAction();
}
public static void Main()
{
// using anonymous delegate
DoWork(delegate() { Console.WriteLine("Completed"); });
// using Lambda
DoWork(() => Console.WriteLine("Completed"));
}
Both DoWork() calls will end with calling the callback that is passed as a parameter.

How to block until an event is fired in c#

After asking this question, I am wondering if it is possible to wait for an event to be fired, and then get the event data and return part of it. Sort of like this:
private event MyEventHandler event;
public string ReadLine(){ return event.waitForValue().Message; }
...
event("My String");
...elsewhere...
var resp = ReadLine();
Please make sure whatever solution you provide returns the value directly rather than getting it from something else. I'm asking if the method above is available in some way. I know about Auto/ManuelResetEvent, but I don't know that they return the value directly like I did above.
Update: I declared an event using MyEventHandler (which contains a Message field). I have a method in another thread called ReadLine waiting for the event to fire. When the event fires the WaitForValue method (part of the event handling scene) returns the event args, which contains the message. The message is then returned by ReadLine to whatever had called it.
The accepted answer to that question I asked was what I did, but it just doesn't feel quite right. It almost feels like something could happen to the data between the ManuelResetEvent firing and the program retrieving the data and returning it.
Update: The main problem with the Auto/ManualResetEvent is that it is too vulnerable. A thread could wait for the event, and then not give enough time for anyone else to get it before changing it to something else. Is there a way to use locks or something else? Maybe using get and set statements.
If the current method is async then you can use TaskCompletionSource. Create a field that the event handler and the current method can access.
TaskCompletionSource<bool> tcs = null;
private async void Button_Click(object sender, RoutedEventArgs e)
{
tcs = new TaskCompletionSource<bool>();
await tcs.Task;
WelcomeTitle.Text = "Finished work";
}
private void Button_Click2(object sender, RoutedEventArgs e)
{
tcs?.TrySetResult(true);
}
This example uses a form that has a textblock named WelcomeTitle and two buttons. When the first button is clicked it starts the click event but stops at the await line. When the second button is clicked the task is completed and the WelcomeTitle text is updated. If you want to timeout as well then change
await tcs.Task;
to
await Task.WhenAny(tcs.Task, Task.Delay(25000));
if (tcs.Task.IsCompleted)
WelcomeTitle.Text = "Task Completed";
else
WelcomeTitle.Text = "Task Timed Out";
You can use ManualResetEvent. Reset the event before you fire secondary thread and then use the WaitOne() method to block the current thread. You can then have secondary thread set the ManualResetEvent which would cause the main thread to continue. Something like this:
ManualResetEvent oSignalEvent = new ManualResetEvent(false);
void SecondThread(){
//DoStuff
oSignalEvent.Set();
}
void Main(){
//DoStuff
//Call second thread
System.Threading.Thread oSecondThread = new System.Threading.Thread(SecondThread);
oSecondThread.Start();
oSignalEvent.WaitOne(); //This thread will block here until the reset event is sent.
oSignalEvent.Reset();
//Do more stuff
}
A very easy kind of event you can wait for is the ManualResetEvent, and even better, the ManualResetEventSlim.
They have a WaitOne() method that does exactly that. You can wait forever, or set a timeout, or a "cancellation token" which is a way for you to decide to stop waiting for the event (if you want to cancel your work, or your app is asked to exit).
You fire them calling Set().
Here is the doc.
If you're happy to use the Microsoft Reactive Extensions, then this can work nicely:
public class Foo
{
public delegate void MyEventHandler(object source, MessageEventArgs args);
public event MyEventHandler _event;
public string ReadLine()
{
return Observable
.FromEventPattern<MyEventHandler, MessageEventArgs>(
h => this._event += h,
h => this._event -= h)
.Select(ep => ep.EventArgs.Message)
.First();
}
public void SendLine(string message)
{
_event(this, new MessageEventArgs() { Message = message });
}
}
public class MessageEventArgs : EventArgs
{
public string Message;
}
I can use it like this:
var foo = new Foo();
ThreadPoolScheduler.Instance
.Schedule(
TimeSpan.FromSeconds(5.0),
() => foo.SendLine("Bar!"));
var resp = foo.ReadLine();
Console.WriteLine(resp);
I needed to call the SendLine message on a different thread to avoid locking, but this code shows that it works as expected.
Try it : e.Handled = true; It works to prevent KeyEventArgs, for example.

Reactive Framework (RX) and dealing with events Asynchronously

So I'm just playing around with RX and learning it. I started playing with Events, and wanted to know how to subscribe to events, and process the results in batches asynchronously. Allow me to explain with code:
Simple class that raises events:
public class EventRaisingClass
{
public event EventHandler<SomeEventArgs> EventOccured;
//some other code that raises event...
}
public class SomeEventArgs : EventArgs
{
public SomeEventArgs(int data)
{
this.SomeArg = data;
}
public int SomeArg { get; private set; }
}
Then my Main:
public static void Main(string[] args)
{
var eventRaiser = new EventRaisingClass();
IObservable<IEvent<SomeEventArgs>> observable =
Observable.FromEvent<SomeEventArgs>(e => eventRaiser.EventOccured += e, e => eventRaiser.EventOccured -= e);
IObservable<IList<IEvent<SomeEventArgs>>> bufferedEvents = observable.BufferWithCount(100);
//how can I subscribte to bufferedEvents so that the subscription code gets called Async?
bufferedEvents.Subscribe(list => /*do something with list of event args*/); //this happens synchrounously...
}
As you can see in my comments, when you just call subscribe like that, all the subscription code happens synchronously. Is there a way out of the box using RX to have the Subscribe be called on different threads whenever there's a new batch of events to work on?
bufferedEvents.ObserveOn(Scheduler.TaskPool).Subscribe(...
SubscribeOn is to specify the schedule on which so-called "subscription side effects" are happening. For example, your observable can open a file each time somebody subscribes.
ObserveOn is to specify the schedule on which the call to the observer will happen every time when there is a new value. In practice, it is used more often than SubscribeOn.
I believe you're looking for SubscribeOn or ObserveOn, passing an IScheduler. There are several schedulers built-in under System.Concurrency; some of them use whatever thread is current, and others use specific threads.
This video has more info on the scheduler concept.
The Rx team also recently released a hands-on labs document which is the closest thing to a tutorial right now.

Categories