当前位置: 首页>>代码示例>>C#>>正文


C# DataReader.LoadAsync方法代码示例

本文整理汇总了C#中Windows.Storage.Streams.DataReader.LoadAsync方法的典型用法代码示例。如果您正苦于以下问题:C# DataReader.LoadAsync方法的具体用法?C# DataReader.LoadAsync怎么用?C# DataReader.LoadAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Windows.Storage.Streams.DataReader的用法示例。


在下文中一共展示了DataReader.LoadAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: OnConnection

        private static async void OnConnection(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            ConnectionStatus = ConnectionStatus.Connected;
            DataReader reader = new DataReader(args.Socket.InputStream);
            try
            {
                while (true)
                {
                    uint sizeFieldCount = await reader.LoadAsync(sizeof (uint));
                    if (sizeFieldCount != sizeof (uint))
                    {
                        return;
                    }
                    
                    uint stringLength = reader.ReadUInt32();
                    uint actualStringLength = await reader.LoadAsync(stringLength);
                    if (stringLength != actualStringLength)
                    {
                        return;
                    }

                    Message = reader.ReadString(actualStringLength);
                }
            }
            catch (Exception e)
            {
                ConnectionStatus = ConnectionStatus.Failed;
                //TODO:send a connection status message with error
            }
        }
开发者ID:95strat,项目名称:GoPiGoWin10,代码行数:30,代码来源:SocketConnection.cs

示例2: ReceiveImage

        private async void ReceiveImage(StreamSocket socket)
        {
            UpdateStatus("Empfange Daten...");

            // DataReader erzeugen, um arbeiten mit Bytes zu vereinfachen
            var reader = new DataReader(socket.InputStream);

            // Anzahl der Bytes abrufen, aus denen das Bild besteht
            // Anzahl = int = 4 Bytes => 4 Bytes vom Socket laden
            await reader.LoadAsync(4);
            int imageSize = reader.ReadInt32();

            // Bytearray des Bildes laden
            await reader.LoadAsync((uint)imageSize);
            byte[] imageBytes = new byte[imageSize];
            reader.ReadBytes(imageBytes);

            // Bytearray in Stream laden und anzeigen
            Dispatcher.BeginInvoke(() =>
            {
                using (var ms = new MemoryStream(imageBytes))
                {
                    var image = new BitmapImage();
                    image.SetSource(ms);

                    ReceivedImage.Source = image;
                }
            });
            UpdateStatus("Bild empfangen.");

            // Ressourcen freigeben
            reader.Dispose();
        }
开发者ID:GregOnNet,项目名称:WP8BookSamples,代码行数:33,代码来源:ClientPage.xaml.cs

示例3: StreamSkeleton

		private async void StreamSkeleton()
		{
			try
			{
                var reader = new DataReader( Client.InputStream );
                reader.InputStreamOptions = InputStreamOptions.Partial;

                while ( IsConnected ) {
                    await reader.LoadAsync( 4 );
                    var size = reader.ReadUInt32();

                    await reader.LoadAsync( size );
                    byte[] bytes = new byte[size];
                    reader.ReadBytes( bytes );

                    MemoryStream ms = new MemoryStream( bytes );
					BinaryReader br = new BinaryReader(ms);

					SkeletonFrameData frame = br.ReadSkeletonFrame();

					SkeletonFrameReadyEventArgs args = new SkeletonFrameReadyEventArgs { SkeletonFrame = frame };
					SkeletonFrame = frame;

					Context.Send(delegate
					{
						if(SkeletonFrameReady != null)
							SkeletonFrameReady(this, args);
					}, null);
				}
			}
			catch(IOException)
			{
                Disconnect();
			}
		}
开发者ID:kaorun55,项目名称:KinectService,代码行数:35,代码来源:SkeletonClient.cs

示例4: DoCommand

 private async Task<string> DoCommand(string command)
 {
     StringBuilder strBuilder = new StringBuilder();
     using (StreamSocket clientSocket = new StreamSocket())
     {
         await clientSocket.ConnectAsync(new HostName("192.168.9.108"),  "9001");
         using (DataWriter writer = new DataWriter(clientSocket.OutputStream))
         {
             writer.WriteString(command);
             await writer.StoreAsync();
             writer.DetachStream();
         }
         using (DataReader reader = new DataReader(clientSocket.InputStream))
         {
             reader.InputStreamOptions = InputStreamOptions.Partial;
             await reader.LoadAsync(8192);
             while (reader.UnconsumedBufferLength > 0)
             {
                 strBuilder.Append(reader.ReadString(reader.UnconsumedBufferLength));
                 await reader.LoadAsync(8192);
             }
             reader.DetachStream();
         }
     }
     return (strBuilder.ToString());
 }
开发者ID:mderoode,项目名称:OVCClient,代码行数:26,代码来源:SocketConnection.xaml.cs

示例5: ColorThread

		private async void ColorThread()
		{
			try
			{
                var reader = new DataReader( Client.InputStream );
                reader.InputStreamOptions = InputStreamOptions.Partial;
                reader.ByteOrder = ByteOrder.LittleEndian;

                while ( IsConnected ) {
                    await reader.LoadAsync( 4 );
                    var size = reader.ReadUInt32();

                    await reader.LoadAsync( size );
                    byte[] bytes = new byte[size];
                    reader.ReadBytes( bytes );

                    MemoryStream ms = new MemoryStream( bytes );
					BinaryReader br = new BinaryReader(ms);

                    ColorFrameReadyEventArgs args = new ColorFrameReadyEventArgs();
                    ColorFrameData cfd = new ColorFrameData();

                    cfd.Format = (ImageFormat)br.ReadInt32();
					cfd.ImageFrame = br.ReadColorImageFrame();

                    MemoryStream msData = new MemoryStream( bytes, (int)ms.Position, (int)(ms.Length - ms.Position) );
                    if (cfd.Format == ImageFormat.Raw)
                    {
                        cfd.RawImage = ms.ToArray();
                    }
                    else
                    {
                        InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream();
                        DataWriter dw = new DataWriter(ras.GetOutputStreamAt(0));
                        dw.WriteBytes(msData.ToArray());
                        await dw.StoreAsync();   

                        // Set to the image
                        BitmapImage bImg = new BitmapImage();
                        bImg.SetSource(ras);
                        cfd.BitmapImage = bImg;
                    }

					ColorFrame = cfd;
					args.ColorFrame = cfd;

                    if (ColorFrameReady != null)
                    {
                        ColorFrameReady(this, args);
                    }
				}
			}
			catch(IOException)
			{
				Disconnect();
			}
		}
开发者ID:kaorun55,项目名称:KinectService,代码行数:57,代码来源:ColorClient.cs

示例6: Listener_ConnectionReceived

        private async void Listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            Debug.WriteLine("Connection Received on Port {0}", sender.Information.LocalPort);
            StreamSocket streamSocket = args.Socket;
            if (streamSocket != null)
            {
                DataReader reader = new DataReader(streamSocket.InputStream);
                try
                {
                    // Read first 4 bytes (length of the subsequent string).
                    uint sizeFieldCount = await reader.LoadAsync(sizeof(uint));
                    if (sizeFieldCount != sizeof(uint))
                    {
                        // The underlying socket was closed before we were able to read the whole data.
                        return;
                    }

                    // Read the length of the 'packet'.
                    uint length = reader.ReadUInt32();
                    uint actualLength = await reader.LoadAsync(length);
                    if (length != actualLength)
                    {
                        // The underlying socket was closed before we were able to read the whole data.
                        return;
                    }

                    string name = reader.ReadString(actualLength);
                    Speaker speaker = new Speaker()
                    {
                        Name = name,
                        Address = streamSocket.Information.RemoteAddress.DisplayName,
                        Status = "Connected",
                        Socket = streamSocket
                    };

                    await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                    () =>
                    {
                        Speakers.Add(speaker);
                    });

                    reader.DetachStream();

                    Debug.WriteLine("New speaker added " + name);

                }
                catch (Exception e)
                {
                    Debug.WriteLine("Error in connection received: " + e);
                }
            }
        }
开发者ID:CHS982,项目名称:Coding4Fun,代码行数:52,代码来源:Publisher.cs

示例7: DepthThread

        private async void DepthThread()
        {
            try {
                short[] depthShort = null;

                var reader = new DataReader( Client.InputStream );
                reader.InputStreamOptions = InputStreamOptions.Partial;

                while ( IsConnected ) {
                    await reader.LoadAsync( 4 );
                    var size = reader.ReadUInt32();

                    await reader.LoadAsync( size );
                    byte[] bytes = new byte[size];
                    reader.ReadBytes( bytes );

                    MemoryStream ms = new MemoryStream( bytes );
                    BinaryReader br = new BinaryReader( ms );

                    DepthFrameData dfd = new DepthFrameData();
                    dfd.PlayerIndexBitmask = br.ReadInt32();
                    dfd.PlayerIndexBitmaskWidth = br.ReadInt32();

                    DepthImageFrame frame = br.ReadDepthImageFrame();
                    dfd.ImageFrame = frame;

                    int dataLength = (int)(ms.Length - ms.Position);

                    if ( depthShort == null || depthShort.Length != dataLength / 2 )
                        depthShort = new short[dataLength / 2];

                    Buffer.BlockCopy( bytes, (int)br.BaseStream.Position, depthShort, 0, dataLength );

                    dfd.DepthData = depthShort;

                    DepthFrame = dfd;

                    DepthFrameReadyEventArgs args = new DepthFrameReadyEventArgs();
                    args.DepthFrame = dfd;

                    Context.Send( delegate
                    {
                        if ( DepthFrameReady != null )
                            DepthFrameReady( this, args );
                    }, null );
                }
            }
            catch ( IOException ) {
                Disconnect();
            }
        }
开发者ID:kaorun55,项目名称:KinectService,代码行数:51,代码来源:DepthClient.cs

示例8: WaitForData

        public async Task WaitForData()
        {
            var mainPageViewModel = MainPageViewModel.GetInstance();

            using (var dr = new DataReader(ServerProxy.TcpSocket.InputStream))
            {
                while (mainPageViewModel.ConnectionStatus)
                {
                    var stringHeader = await dr.LoadAsync(4);

                    if (stringHeader == 0)
                    {
                        mainPageViewModel.ConnectionStatus = false;
                        return;
                    }

                    int messageLength = dr.ReadInt32();
                    uint numBytes = await dr.LoadAsync((uint)messageLength);

                    var packetBaseBuffer = new byte[numBytes];

                    dr.ReadBytes(packetBaseBuffer);

                    var packetBase = new PacketBase();

                    using (var stream = new MemoryStream(packetBaseBuffer))
                    {
                        try
                        {
                            var reader = new BinaryReader(stream);

                            packetBase.Read(reader);
                        }
                        catch (Exception e)
                        {
#if DEBUG
                            throw;
#endif
                        }
                    }


                    var incomingMessage = IncomingMessageFactory.GetMessage(
                        packetBase.Data as PacketV1);

                    incomingMessage.HandleMessage();
                }
            }
        }
开发者ID:jonathanyeung,项目名称:ozwego,代码行数:49,代码来源:MessageReceiver.cs

示例9: AsRandomAccessStreamAsync

        public async static Task<IRandomAccessStream> AsRandomAccessStreamAsync(this Stream stream)
        {
            Stream streamToConvert = null;

            if (!stream.CanRead)
            {
                throw new Exception("Cannot read the source stream-");
            }
            if (!stream.CanSeek)
            {
                MemoryStream memoryStream = new MemoryStream();
                await stream.CopyToAsync(memoryStream);
                streamToConvert = memoryStream;
            }
            else
            {
                streamToConvert = stream;
            }

            DataReader dataReader = new DataReader(streamToConvert.AsInputStream());
            streamToConvert.Position = 0;
            await dataReader.LoadAsync((uint)streamToConvert.Length);
            IBuffer buffer = dataReader.ReadBuffer((uint)streamToConvert.Length);

            InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();
            IOutputStream outputstream = randomAccessStream.GetOutputStreamAt(0);
            await outputstream.WriteAsync(buffer);
            await outputstream.FlushAsync();

            return randomAccessStream;
        }
开发者ID:uwe-e,项目名称:BSE.Tunes,代码行数:31,代码来源:StreamExtensions.cs

示例10: ReadFromStreamButton_Click

 private async void ReadFromStreamButton_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         rootPage.ResetScenarioOutput(OutputTextBlock);
         StorageFile file = rootPage.sampleFile;
         if (file != null)
         {
             using (IRandomAccessStream readStream = await file.OpenAsync(FileAccessMode.Read))
             {
                 using (DataReader dataReader = new DataReader(readStream))
                 {
                     UInt64 size = readStream.Size;
                     if (size <= UInt32.MaxValue)
                     {
                         UInt32 numBytesLoaded = await dataReader.LoadAsync((UInt32)size);
                         string fileContent = dataReader.ReadString(numBytesLoaded);
                         OutputTextBlock.Text = "The following text was read from '" + file.Name + "' using a stream:" + Environment.NewLine + Environment.NewLine + fileContent;
                     }
                     else
                     {
                         OutputTextBlock.Text = "File " + file.Name + " is too big for LoadAsync to load in a single chunk. Files larger than 4GB need to be broken into multiple chunks to be loaded by LoadAsync.";
                     }
                 }
             }
         }
     }
     catch (FileNotFoundException)
     {
         rootPage.NotifyUserFileNotExist();
     }
 }
开发者ID:mac10688,项目名称:PublicWorkspace,代码行数:32,代码来源:Scenario4.xaml.cs

示例11: ReadFromStreamButton_Click

 private async void ReadFromStreamButton_Click(object sender, RoutedEventArgs e)
 {
     StorageFile file = rootPage.sampleFile;
     if (file != null)
     {
         try
         {
             using (IRandomAccessStream readStream = await file.OpenAsync(FileAccessMode.Read))
             {
                 using (DataReader dataReader = new DataReader(readStream))
                 {
                     UInt64 size = readStream.Size;
                     if (size <= UInt32.MaxValue)
                     {
                         UInt32 numBytesLoaded = await dataReader.LoadAsync((UInt32)size);
                         string fileContent = dataReader.ReadString(numBytesLoaded);
                         rootPage.NotifyUser(String.Format("The following text was read from '{0}' using a stream:{1}{2}", file.Name, Environment.NewLine, fileContent), NotifyType.StatusMessage);
                     }
                     else
                     {
                         rootPage.NotifyUser(String.Format("File {0} is too big for LoadAsync to load in a single chunk. Files larger than 4GB need to be broken into multiple chunks to be loaded by LoadAsync.", file.Name), NotifyType.ErrorMessage);
                     }
                 }
             }
         }
         catch (FileNotFoundException)
         {
             rootPage.NotifyUserFileNotExist();
         }
     }
     else
     {
         rootPage.NotifyUserFileNotExist();
     }
 }
开发者ID:ckc,项目名称:WinApp,代码行数:35,代码来源:Scenario5_WriteAndReadAFileUsingAStream.xaml.cs

示例12: Read

 private async Task<RfidReaderResult> Read()
 {
     RfidReaderResult retvalue = new RfidReaderResult();
     var dataReader = new DataReader(_rfidReader.InputStream);
     try
     {
         SetStatus("Awaiting Data from RFID Reader");
         var numBytesRecvd = await dataReader.LoadAsync(1024);
         retvalue.Result = new byte[numBytesRecvd];
         if (numBytesRecvd > 0)
         {
             SetStatus("Data successfully read from RFID Reader");
             dataReader.ReadBytes(retvalue.Result);
             retvalue.IsSuccessful = true;
             retvalue.Message = "Data successfully read from RFID Reader";
         }
     }
     catch (Exception ex)
     {
         retvalue.IsSuccessful = false;
         retvalue.Message = ex.Message;
     }
     finally
     {
         if (dataReader != null)
         {
             dataReader.DetachStream();
             dataReader = null;
         }
     }
     return retvalue;
 }
开发者ID:codingbandit,项目名称:CottonwoodSerialTester,代码行数:32,代码来源:MainPage.xaml.cs

示例13: Read

        public async Task<IEnumerable<Event>> Read() 
        {
            List<Event> events = null;
            StorageFolder localFolder = ApplicationData.Current.LocalFolder;
            try
            {
                StorageFile textFile = await localFolder.GetFileAsync("SavedContent");
                events = new List<Event>();
                using (IRandomAccessStream textStream = await textFile.OpenReadAsync())
                {
                    using (DataReader textReader = new DataReader(textStream))
                    {
                        uint textLength = (uint)textStream.Size;
                        await textReader.LoadAsync(textLength);
                        string jsonContents = textReader.ReadString(textLength);
                        events = JsonConvert.DeserializeObject<IList<Event>>(jsonContents) as List<Event>;
                    }
                    return events;
                }
            }
            catch (Exception ex)
            {
                return null;
            }

        }
开发者ID:mjtpena,项目名称:Aevents,代码行数:26,代码来源:LocalStorageService.cs

示例14: OnOpen

        public async void OnOpen()
        {
            try
            {
                var picker = new FileOpenPicker()
                {
                    SuggestedStartLocation = PickerLocationId.DocumentsLibrary
                };
                picker.FileTypeFilter.Add(".txt");

                StorageFile file = await picker.PickSingleFileAsync();
                if (file != null)
                {
                    IRandomAccessStreamWithContentType stream = await file.OpenReadAsync();
                    using (var reader = new DataReader(stream))
                    {
                        await reader.LoadAsync((uint)stream.Size);

                        text1.Text = reader.ReadString((uint)stream.Size);
                    }
                }
            }
            catch (Exception ex)
            {
                var dlg = new MessageDialog(ex.Message, "Error");
                await dlg.ShowAsync();
            }
        }
开发者ID:ProfessionalCSharp,项目名称:ProfessionalCSharp6,代码行数:28,代码来源:MainPage.xaml.cs

示例15: OpenGraphFile_Click

        async private void OpenGraphFile_Click(object sender, RoutedEventArgs e)
        {
            var picker = new FileOpenPicker();
            picker.FileTypeFilter.Add(".txt");
            picker.ViewMode = PickerViewMode.Thumbnail;
            picker.SettingsIdentifier = "GraphPicker";
            picker.CommitButtonText = "Select Files";

            var selectedFile = await picker.PickSingleFileAsync();
            using (IRandomAccessStream stream = await selectedFile.OpenReadAsync())
            {
                using (DataReader reader = new DataReader(stream))
                {
                    uint length = (uint)stream.Size;
                    await reader.LoadAsync(length);
                    string[] s = reader.ReadString(length).Split('\r');
                    string[][] str = new string[s.Length][];
                    for (int i = 0; i < s.Length; i++)
                        str[i] = s[i].Replace('\n', ' ').Split(' ');
                    int n = int.Parse(s[0]);
                    int[,] adjMatrix = new int[n, n];
                    for (int i = 0; i < n; i++)
                        for (int j = 0; j < n; j++)
                            adjMatrix[i, j] = int.Parse(str[i + 1][j + 1]);
                    adjMatrix[0, 0] += 0;
                    graph = new Graph(adjMatrix, n);
                }
            }
        }
开发者ID:nikitaneo,项目名称:Labs,代码行数:29,代码来源:MainPage.xaml.cs


注:本文中的Windows.Storage.Streams.DataReader.LoadAsync方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。