使用Channel传递数据

发布时间 2023-10-23 16:27:16作者: 孤沉

上次我们使用了事件异步传递数据,这次我们使用Channel在一个线程通信传递数据
直接上代码

 public static class ChannelSample
 {
     private static readonly Channel<KeyValuePair<string, string>> channel = Channel.CreateUnbounded<KeyValuePair<string, string>>();

     public static void SetLocalValue(string name, string value)
     {
         channel.Writer.TryWrite(new KeyValuePair<string, string>(name, value));
     }

     public static string GetLocalValue(string name)
     {
         while (channel.Reader.TryRead(out KeyValuePair<string, string> item))
         {
             if (item.Key == name)
             {
                 return item.Value;
             }
         }
         return null;
     }
 }

 public class WriteSample
 {
     public void Write() 
     {
         ChannelSample.SetLocalValue("name","Hello");
     }
 }
 public class ReadSample
 {
     public void Read()
     {
         ChannelSample.GetLocalValue("name");
     }
 }

首先我们自己封装一个静态类,它有着写入和发送的功能,这样在需要的地方可以将数据传递过去
在上述代码中,我们在WriteSample类中使用我们封装好的静态类写了Hello,并且为它取名name
接着在ReadSample类中拿到Hello,
它不能用在异步,你可以封装完善它,扩展它