本文整理汇总了C#中System.IO.StreamWriter.FlushAsync方法的典型用法代码示例。如果您正苦于以下问题:C# StreamWriter.FlushAsync方法的具体用法?C# StreamWriter.FlushAsync怎么用?C# StreamWriter.FlushAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.IO.StreamWriter
的用法示例。
在下文中一共展示了StreamWriter.FlushAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ClientWork
private async void ClientWork(object state)
{
int clientId = (int)state;
using (var channel = this.connection.ConnectChannel())
{
using (StreamWriter writer = new StreamWriter(channel))
{
using (StreamReader reader = new StreamReader(channel))
{
string request = string.Format("Hello from {0}", clientId);
string response;
await writer.WriteLineAsync(request);
await writer.FlushAsync();
response = await reader.ReadLineAsync();
await writer.WriteLineAsync(request);
await writer.FlushAsync();
response = await reader.ReadLineAsync();
await channel.StopSendingAsync();
await channel.FlushAsync();
if (reader.EndOfStream)
{
Console.WriteLine("Client feel right!");
}
}
}
}
if (Interlocked.Decrement(ref pendingCount) == 0)
{
lock (termLock)
{
Monitor.Pulse(termLock);
}
}
}
示例2: WorkAsync
private static async Task WorkAsync(Channel channel)
{
using (channel)
{
using (var reader = new StreamReader(channel))
{
using (var writer = new StreamWriter(channel))
{
string request = await reader.ReadLineAsync();
await writer.WriteLineAsync(request);
await writer.FlushAsync();
request = await reader.ReadLineAsync();
await writer.WriteLineAsync(request);
await writer.FlushAsync();
Console.WriteLine("Server waiting for close");
if (reader.EndOfStream)
{
Console.WriteLine("Server feel right!");
}
await channel.StopSendingAsync();
await channel.FlushAsync();
}
}
}
}
示例3: DoSomethingWithClientAsync
public async Task DoSomethingWithClientAsync()
{
try
{
using (var stream = _client.GetStream())
{
using (var sr = new StreamReader(stream))
using (var sw = new StreamWriter(stream))
{
await sw.WriteLineAsync("Hi. This is x2 TCP/IP easy-to-use server").ConfigureAwait(false);
await sw.FlushAsync().ConfigureAwait(false);
var data = default(string);
while (!((data = await sr.ReadLineAsync().ConfigureAwait(false)).Equals("exit", StringComparison.OrdinalIgnoreCase)))
{
await sw.WriteLineAsync(data).ConfigureAwait(false);
await sw.FlushAsync().ConfigureAwait(false);
}
}
}
}
finally
{
if (_ownsClient && _client != null)
{
(_client as IDisposable).Dispose();
_client = null;
}
}
}
示例4: SerializeToStreamAsync
protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
using (var writer = new StreamWriter(stream))
{
await writer.WriteAsync("data: { \"Type\": \"Heartbeat\" }\r\n\r\n");
await writer.FlushAsync();
while (Connected)
{
try
{
var result = await manualResetEvent.WaitAsync(5000);
if (Connected == false)
return;
if (result == false)
{
await writer.WriteAsync("data: { \"Type\": \"Heartbeat\" }\r\n\r\n");
await writer.FlushAsync();
if (lastMessageEnqueuedAndNotSent != null)
{
await SendMessage(lastMessageEnqueuedAndNotSent, writer);
}
continue;
}
manualResetEvent.Reset();
object message;
while (msgs.TryDequeue(out message))
{
if (CoolDownWithDataLossInMiliseconds > 0 && Environment.TickCount - lastMessageSentTick < CoolDownWithDataLossInMiliseconds)
{
lastMessageEnqueuedAndNotSent = message;
continue;
}
await SendMessage(message, writer);
}
}
catch (Exception e)
{
Connected = false;
log.DebugException("Error when using events transport", e);
Disconnected();
try
{
writer.WriteLine(e.ToString());
}
catch (Exception)
{
// try to send the information to the client, okay if they don't get it
// because they might have already disconnected
}
}
}
}
}
示例5: WriteToStreamAsync
public override async Task WriteToStreamAsync(Type type, object value, Stream stream, HttpContent content, TransportContext transportContext)
{
using (stream)
{
Encoding encoding = SelectCharacterEncoding(content.Headers);
using (var writer = new StreamWriter(stream, encoding))
{
var individuals = value as IEnumerable<Individual>;
if (individuals != null)
{
foreach (var individu in individuals)
{
await writer.WriteLineAsync(String.Format("{0,-10};{1,-10};{2,-10}", individu.Id, individu.FirstName, individu.LastName));
}
await writer.FlushAsync();
}
var individual = value as Individual;
if (individual != null)
{
await writer.WriteLineAsync(String.Format("{0,-10};{1,-10};{2,-10}", individual.Id, individual.FirstName, individual.LastName));
await writer.FlushAsync();
}
}
}
}
示例6: SerializeToStreamAsync
protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
using (var writer = new StreamWriter(stream))
{
await writer.WriteAsync("data: { \"Type\": \"Heartbeat\" }\r\n\r\n");
await writer.FlushAsync();
while (Connected)
{
try
{
var result = await manualResetEvent.WaitAsync(5000);
if (Connected == false)
return;
if (result == false)
{
await writer.WriteAsync("data: { \"Type\": \"Heartbeat\" }\r\n\r\n");
await writer.FlushAsync();
continue;
}
manualResetEvent.Reset();
object message;
while (msgs.TryDequeue(out message))
{
var obj = JsonConvert.SerializeObject(message, Formatting.None, new EtagJsonConverter());
await writer.WriteAsync("data: ");
await writer.WriteAsync(obj);
await writer.WriteAsync("\r\n\r\n");
await writer.FlushAsync();
}
}
catch (Exception e)
{
Connected = false;
log.DebugException("Error when using events transport", e);
Disconnected();
try
{
writer.WriteLine(e.ToString());
}
catch (Exception)
{
// try to send the information to the client, okay if they don't get it
// because they might have already disconnected
}
}
}
}
}
示例7: Listen
protected async Task Listen(Socket socket) {
Stream ioStream = socket.GetStream();
StreamReader reader = new StreamReader(ioStream);
StreamWriter writer = new StreamWriter(ioStream);
await writer.WriteLineAsync(FtpResponse.PositiveCompletionReply.ServiceReady.ToString());
await writer.FlushAsync();
string command;
while (true) {
string result = await RunCommand(await reader.ReadLineAsync());
await writer.WriteLineAsync(result);
await writer.FlushAsync();
}
}
示例8: Get
public HttpResponseMessage Get()
{
var resp = new HttpResponseMessage
{
Content = new PushStreamContent(async (respStream, content, context) =>
{
try
{
var wordsToSend = Lipsum.Split(' ');
using (var writer = new StreamWriter(respStream))
{
foreach (var word in wordsToSend)
{
await writer.WriteLineAsync(word);
await writer.FlushAsync();
await Task.Delay(millisecondsDelay: 250);
}
}
}
catch (Exception ex)
{
return;
}
finally
{
respStream.Close();
}
}, "text/plain")
};
return resp;
}
示例9: WriteBody
public async Task WriteBody(StreamWriter writer)
{
_memoryStream.Position = 0;
await writer.FlushAsync().ConfigureAwait(false);
await _memoryStream.CopyToAsync(writer.BaseStream).ConfigureAwait(false);
}
示例10: Invoke
public override async Task Invoke(IOwinContext context)
{
// process response
var owinResponse = new OwinResponse(context.Environment) { ContentType = "text/plain" };
var owinRequest = new OwinRequest(context.Environment);
var writer = new StreamWriter(owinResponse.Body);
switch (owinRequest.Path.Value)
{
case "/root/10mbTest.txt":
writer.Write(TestHelpers.FileContent5bTest);
owinResponse.ContentLength = TestHelpers.FileContent5bTest.Length;
break;
case "/root/simpleTest.txt":
writer.Write(TestHelpers.FileContentSimpleTest);
owinResponse.ContentLength = TestHelpers.FileContentSimpleTest.Length;
break;
case "/root/index.html":
writer.Write(TestHelpers.FileContentIndex);
owinResponse.ContentLength = TestHelpers.FileContentIndex.Length;
break;
case "/root/emptyFile.txt":
writer.Write(TestHelpers.FileContentEmptyFile);
owinResponse.ContentLength = TestHelpers.FileContentEmptyFile.Length;
break;
default:
writer.Write(TestHelpers.FileContentAnyFile);
owinResponse.ContentLength = TestHelpers.FileContentAnyFile.Length;
break;
}
await writer.FlushAsync();
}
示例11: SendRPCAsync
async Task<string> SendRPCAsync(string methodName, params object[] args) {
var jsonArgs = new List<string>();
foreach(var arg in args) {
if(arg is string) {
jsonArgs.Add(String.Format("\"{0}\"", arg));
}
else {
jsonArgs.Add(arg.ToString());
}
}
var rpc = String.Format("{{\"id\": 1, \"method\": \"{0}\", \"params\": [{1}]}}", methodName, String.Join(", ", jsonArgs));
await ClientLock.WaitAsync();
try {
var writer = new StreamWriter(ClientStream);
await writer.WriteLineAsync(rpc);
await writer.FlushAsync();
var reader = new StreamReader(ClientStream);
return await reader.ReadLineAsync();
}
finally {
ClientLock.Release();
}
}
示例12: SerializeToStreamAsync
protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
string jsonString = await JsonConvert.SerializeObjectAsync(this.JsonObject);
StreamWriter writer = new StreamWriter(stream);
await writer.WriteAsync(jsonString);
await writer.FlushAsync();
}
示例13: InsertOrUpdate
public async Task<bool> InsertOrUpdate(KeyVaultConfiguration keyVaultConfiguration)
{
var writeToFile = JsonConvert.SerializeObject(keyVaultConfiguration);
var filePath = Path.Combine(
ConfigurationPath,
keyVaultConfiguration.VaultName,
string.Format(ConfigurationFileFormat, keyVaultConfiguration.VaultName));
var directoryPath = Path.Combine(ConfigurationPath, keyVaultConfiguration.VaultName);
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
using (var file = File.Create(filePath))
{
using (var streamWriter = new StreamWriter(file))
{
await streamWriter.WriteAsync(writeToFile);
await streamWriter.FlushAsync();
this.allConfigurations.Remove(keyVaultConfiguration);
this.allConfigurations.Add(keyVaultConfiguration);
return true;
}
}
}
示例14: RedeemRefreshTokenInternalAsync
private static async Task<TokenResponse> RedeemRefreshTokenInternalAsync(OAuthAccount account)
{
HttpWebRequest request = WebRequest.CreateHttp(account.TokenService);
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
var requestStream = await request.GetRequestStreamAsync();
var writer = new StreamWriter(requestStream);
StringBuilder sb = new StringBuilder();
sb.AppendFormat("client_id={0}", Uri.EscapeDataString(account.ClientId));
sb.AppendFormat("&redirect_uri={0}", Uri.EscapeDataString(account.RedirectUri));
sb.AppendFormat("&client_secret={0}", Uri.EscapeDataString(account.ClientSecret));
sb.AppendFormat("&refresh_token={0}", Uri.EscapeDataString(account.RefreshToken));
sb.Append("&grant_type=refresh_token");
if (null != account.Resource)
sb.AppendFormat("&resource={0}", Uri.EscapeDataString(account.Resource));
var content = sb.ToString();
await writer.WriteAsync(content);
await writer.FlushAsync();
var response = await request.GetResponseAsync() as HttpWebResponse;
if (null != response && response.StatusCode == HttpStatusCode.OK)
{
var responseStream = response.GetResponseStream();
if (null != responseStream)
{
var reader = new StreamReader(responseStream);
return JsonConvert.DeserializeObject<TokenResponse>(await reader.ReadToEndAsync());
}
}
return null;
}
示例15: WriteTextIntoFileAsync
public static async Task<bool> WriteTextIntoFileAsync(string text, StorageFile file)
{
try
{
if (file != null)
{
using (var fileStream = await file.OpenStreamForWriteAsync().ConfigureAwait(false))
{
using (var writer = new StreamWriter(fileStream))
{
fileStream.SetLength(0); // avoid leaving crap at the end if overwriting a file that was longer
fileStream.Seek(0, SeekOrigin.Begin);
await writer.WriteAsync(text).ConfigureAwait(false);
await fileStream.FlushAsync();
await writer.FlushAsync();
return true;
}
}
}
}
catch (Exception ex)
{
await Logger.AddAsync(ex.ToString(), Logger.FileErrorLogFilename).ConfigureAwait(false);
}
return false;
}