每2秒检查一次字符串值是否发生变化。

huangapple go评论80阅读模式
英文:

Check every 2 seconds if a string value is changed

问题

I want to check myString every 2 seconds to itself to see if its changed. myString if influenced by other code

我想每隔2秒检查myString自身是否发生了变化。myString受其他代码影响。

I'm wondering if we have to store myString every 2 seconds somewhere else (lets say X) and then compare X to myString

我在想是否需要每隔2秒将myString存储在其他地方(比如X),然后将X与myString进行比较。

英文:

I want to check myString every 2 seconds to itself to see if its changed. myString if influenced by other code

I'm wondering if we have to store myString every 2 seconds somewhere else (lets say X) and then compare X to myString

答案1

得分: 1

以下是翻译好的部分:

你可能只是因为对语言中的功能了解不足而问错了问题。

每2秒检查一次,你可以考虑运行一个单独的任务,延迟2000毫秒并进行检查和执行某些操作。

你可以创建一个后台工作线程来执行类似的任务。

你可以创建公共的getter/setter,以便在它发生变化时采取行动。这样,你就不会浪费资源每两秒检查一次。最后这个选项可能适合你。

你还可以通过公开一个"事件"来实现,该事件公开一个事件处理程序,其他对象可以注册它,因此当发生某些事情时,所有注册到事件的对象都会收到通知。这样,它不仅具有一个输出通道。如果你认为这可能有帮助,我也可以发布该选项。

英文:

You might just be asking the wrong question only due to your lack of knowledge about features in the language.

Checking every 2 seconds, you could look into running a separate task that delays 2000 milliseconds and checks and does something.

You could have a backgroundworker thread doing similar.

You could create public getter/setter so that when it DOES change, you can act on it. This way you dont waste resources checking every two seconds. This last option MIGHT work for you.

public class YourExistingClassSomewhere
{
   private string _myString = "just setting to a default start value";
   public string MyString
   {
      get {return _myString;}
      set {
            // even if attempting to assign a new value,
            // if the incoming new value is the same, just get out.
            if( _myString == value )
               return;

            // it was a different value, save it           
            _myString = value;
            // Then you could call some other method to display message.
            DoWhenStringChanges(); 
         }
   }

   public void DoWhenStringChanges()
   {
      Messagebox.Show( "it changed: " + MyString );
   }


   public YourExistingClassSomewhere()
   {
      MyString = _myString;  // try to set it to its own value, no change made

      MyString = "something new";  // this will trigger the message notification
   }
}

You could ALSO do via exposing an "event" which exposes an event handler that other objects can get registered with, so when something happens, ANYTHING that is registered to the event gets notified. So, it does not have just one output reach. I could post that option as well if you think that might help.

huangapple
  • 本文由 发表于 2023年1月6日 10:56:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/75026514.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定