0

In C# I want to go over a series of template-objects and want the user to select a coordinate in a grid. Now I have an enumerator and I'm moving to the next object in the ClickEventHandler. But as it is more easily readable I think I wanna try it with async/await. (My project is getting pretty big and I need something well strucutured). So currently I have something like this:

    public void OnPositionClicked(object sender, MouseEventArgs e)
    {
        process(((Selection) sender).point, templateEnumerator.Current);
        templateEnumerator.MoveNext();
    }

But I want to have something more human-readable like this

    foreach (var template in templateEnumerator)
    {
        var position = await PositionGotClicked();
        process(position, template);
    }

How would I implement the async PositionGotClicked()-Method/delegate that blocks a seperate thread until the user clicks something?

I hope it is clear what I'm asking, I don't really know a word for it.

Edit - Purpose: The Purpose of this is to create a game of sinking ships. In the selection-mode where you place all of you ships I want to go over the different types (submarines, cruisers, battelships ...) which differ in size. So I have created a class ShipType that specifies how many ships there are of each type, how big each type is, it's color and name. Then I want for each ship-type to let the user select 'n' positions (depending on how many there are of each type) and afterwards go to the next ship, select a position for it and so on.

  • 2
    You're probably looking for TaskCompletionSource. Wire up the mouse event handler with a task completion source and await the task. No extra thread needed :) – Luaan Oct 30 '20 at 16:25
  • Thanks, I'll look into it :) –  Oct 30 '20 at 16:28
  • It's probably not the best intro to async/await that I could think of.. and indeed I think I'd do it completely differently to these (not that it's SO's job to do your design) but the requirements are a bit scant on detail.. – Caius Jard Oct 30 '20 at 16:34
  • @CaiusJard I've edited the question and added the purpose for it. How would you design something like this? I think having the template in a for-loop is way more readable. –  Oct 30 '20 at 16:43
  • Gotta admit I'm even struggling to see how an enumerator fits into this.. If a user can place N ships of type X at random (click aircraft carrier, click square B6, click destroyer, click A1, click frigate, click D5, click destroyer again, click E7..) it doesn't seem a candidate for enumeration... All I see as data containers here are arrays, really – Caius Jard Oct 30 '20 at 16:58
  • Related: [How to await an event click](https://stackoverflow.com/questions/58340162/how-to-await-an-event-click) – Theodor Zoulias Oct 30 '20 at 17:21

0 Answers0