0

I have a class

Public class DDSModel
{
   public string message {get; set;}
}

I'm using this class in c# code

but I want to hold my code execution till the message property is empty.

I have a different method that is filling the property after some time it depends on user it can be filled in 2 seconds or 2 minutes. But as soon as the user fills the message I need to execute where it was hold.

I can use while in this but I just want to use the TaskCompletionSource.

A_Sk
  • 4,532
  • 3
  • 27
  • 51

2 Answers2

1

Let's break down your problem. You want to watch the value of DDSModel.message, and wait until the value has a value of null, then react to it, all using Task.

  1. You want to be able to watch the value of DDSModel.message

Do

 public class DDSModel : INotifyPropertyChanged
 {
     public event PropertyChangedEventHandler PropertyChanged;
     protected void OnPropertyChanged([CallerMemberName] string property)
     {
          PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
     }

     private string _message;
     public string Message
     {
         get { return _message; }
         set { _message = value; OnPropertyChanged(); }
     }
 }

Then you can do:

 public Task WaitUntilMessageIsNull(model DDSModel)
 {
     var tcs = new TaskCompletionSource<int>();
     PropertyChangedEventHandler handler = (o, e) => {
         if(model.Message == null && e.PropertyName == "Message")
         {
            tcs.SetResult(0);
            model.PropertyChanged -= handler;
         }
     }
     model.PropertyChanged += handler;
     return tcs.Task;

 }

However if you want cleaner code, I would recommend using System.Reactive for the logic.

 public Task WaitUntilMessageIsNull(model DDSModel)
 {
     return Observable
            .FromEventPattern<PropertyChangedEventHandler, PropertyChangedEventArgs>(
                h => model.propertyChanged += h,
                h => model.propertyChanged -= h)
            .Where(x => x.EventArgs.PropertyName == "Message")
            .Where(_ => model.Message == null)
            .ToTask();
 }
Aron
  • 15,464
  • 3
  • 31
  • 64
0

u can use C# - Multithreading property to hold the execution

visit here to know how:https://www.tutorialspoint.com/csharp/csharp_multithreading.htm

Atul Mathew
  • 445
  • 3
  • 15