'Wait for user to choose from the backend
I'm coding the backend portion of a software and at some point I need my user to choose some things, it can be a convoluted process, the user can even cancel the selection at any point.
From the back end I'd like to do something like:
private async void StartAction()
{
//some code
var SelectedItem = await UI.RequestUserToChooseItem();
// some final code using the selected item
}
Here I don't know how to handle cancellation, but I can send null and assume that if the SelectedItem is null it was canceled.
But what about the UI portion of it? How do I handle it to return the call when the thing is selected by the user?
I need to perform some steps here: (this is pseudocode, I don't even know where to start)
public List<Item> RequestUserToChooseItem()
{
PrepareItemsInList();
ShowSelectionPanel();
List<Items> SelectedItemsFromPanel = WaitForUserToChose(); //???????
return SelectedItemsFromPanel;
}
And then we have the cancel button:
private void CancelButtonClicked(object sender, EventArgs e)
{
CancelWaitedSelectionProcessAndReturnNull(); //????
}
Solution 1:[1]
Here is an asynchronous method that waits asynchronously for the first click on one or more buttons, and returns the clicked button:
public static Task<Button> OnClickAsync(params Button[] buttons)
{
var tcs = new TaskCompletionSource<Button>();
foreach (var button in buttons) button.Click += OnClick;
return tcs.Task;
void OnClick(object sender, RoutedEventArgs e)
{
foreach (var button in buttons) button.Click -= OnClick;
tcs.SetResult((Button)sender);
}
}
It could be used like this:
public async Task<List<Item>> RequestUserToChooseItemAsync()
{
PrepareItemsInList();
ShowSelectionPanel();
var selectedButton = await OnClickAsync(btnOK, btnCancel);
if (selectedButton == btnCancel) return null;
return SelectedItemsFromPanel;
}
This method should be called exclusively on the UI thread, not on background threads, because it interacts with UI elements.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Theodor Zoulias |
