Created
February 7, 2022 05:02
-
-
Save noseratio/6e1231a0b49329f979af63d59a0531c1 to your computer and use it in GitHub Desktop.
Streaming TextChanged event as IAsyncEnumerable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// verifying https://twitter.com/noseratio/status/1490181545746841602?s=20&t=9FIQA5E2Qz9oHLSEQIW7Ew | |
namespace textbox; | |
using System.Diagnostics; | |
using System.Runtime.CompilerServices; | |
using System.Threading.Channels; | |
static class Program | |
{ | |
[STAThread] | |
static void Main() | |
{ | |
ApplicationConfiguration.Initialize(); | |
Application.Run(new MainForms()); | |
} | |
} | |
public class TextBox: System.Windows.Forms.TextBox | |
{ | |
public async IAsyncEnumerable<EventArgs> OnChanged( | |
[EnumeratorCancellation] | |
CancellationToken cancellationToken) | |
{ | |
var channel = Channel.CreateUnbounded<EventArgs>(); | |
void onTextChanged(object? _, EventArgs e) => | |
channel.Writer.TryWrite(e); | |
this.TextChanged += onTextChanged; | |
try | |
{ | |
await foreach (var ev in channel.Reader.ReadAllAsync(cancellationToken)) | |
{ | |
yield return ev; | |
} | |
} | |
finally | |
{ | |
this.TextChanged -= onTextChanged; | |
channel.Writer.Complete(); | |
} | |
} | |
} | |
public partial class MainForms : Form | |
{ | |
public MainForms() | |
{ | |
InitializeComponent(); | |
var textBox = new TextBox() { Visible = true, Dock = DockStyle.Fill }; | |
this.Controls.Add(textBox); | |
async Task OnChanged() | |
{ | |
await foreach (var onChanged in textBox!.OnChanged(CancellationToken.None)) | |
{ | |
Trace.WriteLine("OnChanged"); | |
} | |
} | |
_ = Task.Run(() => OnChanged()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment