EN VI

How to simulate obtaining user input sequentially using async/await in C#?

2024-03-16 18:30:05
How to simulate obtaining user input sequentially using async/await in C#

Suppose you need to get strings from user input. In a console application, the desired code is straightforward:

string input1 = Console.ReadLine();
string input2 = Console.ReadLine();

However, in my Windows Forms application, I’m working with a Multiline TextBox. I want to capture strings when the user presses the Enter key, with each line separated by a newline.

I’m curious if there’s an Async/Await solution that allows me to handle the KeyPressed event and return user inputs. Ideally, I’d like to achieve something like this:

string input1 = await GetUserInputAsync();
string input2 = await GetUserInputAsync();

Solution:

You can use a semaphore :

    readonly SemaphoreSlim userEnterSemaphore = new SemaphoreSlim(1, 1);

    public Form1()
    {
        InitializeComponent();
    }

    private async Task DoUserFlow()
    {
        // do some stuff

        // Wait semaphore
        await userEnterSemaphore.WaitAsync();

        // do some stuff

    }

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == (char)13)
        {
            userEnterSemaphore.Release();
        }
    }

Semaphore is maybe not exactly for this purpose, but it can work. You can take a look at the AutoResetEvent too which can be very usefull.

// Declare the AutoResetEvent (ManualResetEvent exists too)
AutoResetEvent resetEvent = new AutoResetEvent(false);

// Wait for the event
await Task.Run(() => resetEvent.WaitOne());

// Raise the event on key pressed
if (e.KeyChar == (char)13)
{
    resetEvent.Set();
}

ManualResetEvent can be handy in your situation, you can reset all of your events at the begining of the DoUserFlow method to be sure that any events are not already raised

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login