本文整理汇总了C#中Task.ConfigureAwait方法的典型用法代码示例。如果您正苦于以下问题:C# Task.ConfigureAwait方法的具体用法?C# Task.ConfigureAwait怎么用?C# Task.ConfigureAwait使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Task
的用法示例。
在下文中一共展示了Task.ConfigureAwait方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: AppendStringToLogFile
/// <summary>
/// Appends the provided logString to end of fileName.txt. If the file does not exist it will be created.
/// </summary>
/// <param name="fileName">The filename to use. The extension .txt will be appended automatically</param>
/// <param name="logString">The string to append.</param>
public static void AppendStringToLogFile(string fileName, string logString)
{
try
{
//Catch filenames that are too long
if (fileName.Length > 50)
fileName = fileName.Substring(0, 50);
lock (errorLocker)
{
#if NETFX_CORE
Task writeTask = new Task(async () =>
{
StorageFolder folder = ApplicationData.Current.LocalFolder;
StorageFile file = await folder.CreateFileAsync(fileName + ".txt", CreationCollisionOption.OpenIfExists);
await FileIO.AppendTextAsync(file, logString);
});
writeTask.ConfigureAwait(false);
writeTask.Start();
writeTask.Wait();
#else
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(fileName + ".txt", true))
sw.WriteLine(logString);
#endif
}
}
catch (Exception)
{
//If an error happens here, such as if the file is locked then we lucked out.
}
}
示例2: DownloadStringAsync
async private static void DownloadStringAsync(string uri)
{
var client = new WebClient();
Task<string> task = new Task<string>(() => "do stuff.");
task.ConfigureAwait(false);
task.Start();
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Doing busy work while async operation executes");
Thread.Sleep(100);
}
var result = await task;
Console.WriteLine("Task is finished, read " + result.Length + " characters");
}
示例3: CreateCombinedTask
private async Task<CommandResult> CreateCombinedTask(Task processTask, List<Task> ioTasks)
{
int exitCode;
try
{
await processTask.ConfigureAwait(false);
exitCode = this.process.ExitCode;
}
finally
{
if (this.disposeOnExit)
{
// clean up the process AFTER we capture the exit code
this.process.Dispose();
}
}
await SystemTask.WhenAll(ioTasks).ConfigureAwait(false);
return new CommandResult(exitCode, this);
}
示例4: InnerCalculate
private async Task<IProjectMetric> InnerCalculate(Project project, Task<Compilation> compilationTask, Solution solution)
{
if (project == null)
{
return null;
}
var compilation = await compilationTask.ConfigureAwait(false);
var metricsTask = _metricsCalculator.Calculate(project, solution);
IEnumerable<string> dependencies;
if (solution != null)
{
var dependencyGraph = solution.GetProjectDependencyGraph();
dependencies = dependencyGraph.GetProjectsThatThisProjectTransitivelyDependsOn(project.Id)
.Select<ProjectId, Project>(id => solution.GetProject(id))
.SelectMany(x => x.MetadataReferences.Select(y => y.Display).Concat(new[] { x.AssemblyName }));
}
else
{
dependencies = project.AllProjectReferences.SelectMany(x => x.Aliases)
.Concat(project.MetadataReferences.Select(y => y.Display));
}
var assemblyTypes = compilation.Assembly.TypeNames;
var metrics = (await metricsTask.ConfigureAwait(false)).AsArray();
var internalTypesUsed = from metric in metrics
from coupling in metric.ClassCouplings
where coupling.Assembly == project.AssemblyName
select coupling;
var relationalCohesion = (internalTypesUsed.Count() + 1.0) / assemblyTypes.Count;
return new ProjectMetric(project.Name, metrics, dependencies, relationalCohesion);
}
示例5: WaitForDescriptionChangedAsync
private async Task WaitForDescriptionChangedAsync(IServerSelector selector, ClusterDescription description, Task descriptionChangedTask, TimeSpan timeout, CancellationToken cancellationToken)
{
var cancellationTaskCompletionSource = new TaskCompletionSource<bool>();
using (cancellationToken.Register(() => cancellationTaskCompletionSource.TrySetCanceled()))
using (var timeoutCancellationTokenSource = new CancellationTokenSource())
{
var timeoutTask = Task.Delay(timeout, timeoutCancellationTokenSource.Token);
var completedTask = await Task.WhenAny(descriptionChangedTask, timeoutTask, cancellationTaskCompletionSource.Task).ConfigureAwait(false);
if (completedTask == timeoutTask)
{
ThrowTimeoutException(selector, description);
}
timeoutCancellationTokenSource.Cancel();
if (completedTask == cancellationTaskCompletionSource.Task)
{
cancellationToken.ThrowIfCancellationRequested();
}
await descriptionChangedTask.ConfigureAwait(false); // propagate exceptions
}
}
示例6: Wait
private async Task<IDisposable> Wait(Task wait) {
if (wait.IsCompleted)
return _releaser;
await wait.ConfigureAwait(false);
return _releaser;
}
示例7: FinishSendAsyncBuffered
private async Task<HttpResponseMessage> FinishSendAsyncBuffered(
Task<HttpResponseMessage> sendTask, HttpRequestMessage request, CancellationTokenSource cts, bool disposeCts)
{
HttpResponseMessage response = null;
try
{
// Wait for the send request to complete, getting back the response.
response = await sendTask.ConfigureAwait(false);
if (response == null)
{
throw new InvalidOperationException(SR.net_http_handler_noresponse);
}
// Buffer the response content if we've been asked to and we have a Content to buffer.
if (response.Content != null)
{
await response.Content.LoadIntoBufferAsync(_maxResponseContentBufferSize).ConfigureAwait(false);
}
if (NetEventSource.IsEnabled) NetEventSource.ClientSendCompleted(this, response, request);
return response;
}
catch (Exception e)
{
response?.Dispose();
HandleFinishSendAsyncError(e, cts);
throw;
}
finally
{
HandleFinishSendAsyncCleanup(request, cts, disposeCts);
}
}
示例8: GetFilteredDiagnosticsAsync
private static async Task<ImmutableArray<Diagnostic>> GetFilteredDiagnosticsAsync(Task<IEnumerable<Diagnostic>> getDiagnosticsTask, ImmutableHashSet<string> diagnosticIds)
{
if (getDiagnosticsTask != null)
{
var diagnostics = await getDiagnosticsTask.ConfigureAwait(false);
if (diagnostics != null)
{
return diagnostics.Where(d => d != null && diagnosticIds.Contains(d.Id)).ToImmutableArray();
}
}
return ImmutableArray<Diagnostic>.Empty;
}
示例9: ParseEndElementAsync_Finish
private async Task ParseEndElementAsync_Finish(Task task, int nameLen, NodeData startTagNode, LineInfo endTagLineInfo)
{
while (true)
{
await task.ConfigureAwait(false);
switch (_parseEndElement_NextFunc)
{
case ParseEndElementParseFunction.CheckEndTag:
task = ParseEndElementAsync_CheckEndTag(nameLen, startTagNode, endTagLineInfo);
break;
case ParseEndElementParseFunction.ReadData:
task = ParseEndElementAsync_ReadData();
break;
case ParseEndElementParseFunction.Done:
return;
}
}
}
示例10: CopyToAsyncCore
private async Task CopyToAsyncCore(Task flushTask, Stream destination, int bufferSize, CancellationToken cancellationToken)
{
await flushTask.ConfigureAwait(false);
await _stream.CopyToAsync(destination, bufferSize, cancellationToken).ConfigureAwait(false);
}
示例11: SendRequest
private async Task<WebResponse> SendRequest()
{
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
var handler = new HttpClientHandler();
var client = new HttpClient(handler);
var request = new HttpRequestMessage(new HttpMethod(_originVerb), _requestUri);
if (_requestStream != null)
{
ArraySegment<byte> bytes = _requestStream.GetBuffer();
request.Content = new ByteArrayContent(bytes.Array, bytes.Offset, bytes.Count);
}
// Set to match original defaults of HttpWebRequest.
// HttpClientHandler.AutomaticDecompression defaults to true; set it to false to match the desktop behavior
handler.AutomaticDecompression = DecompressionMethods.None;
handler.Credentials = _credentials;
if (_cookieContainer != null)
{
handler.CookieContainer = _cookieContainer;
Debug.Assert(handler.UseCookies); // Default of handler.UseCookies is true.
}
else
{
handler.UseCookies = false;
}
Debug.Assert(handler.UseProxy); // Default of handler.UseProxy is true.
Debug.Assert(handler.Proxy == null); // Default of handler.Proxy is null.
if (_proxy == null)
{
handler.UseProxy = false;
}
else
{
handler.Proxy = _proxy;
}
// Copy the HttpWebRequest request headers from the WebHeaderCollection into HttpRequestMessage.Headers and
// HttpRequestMessage.Content.Headers.
foreach (string headerName in _webHeaderCollection)
{
// The System.Net.Http APIs require HttpRequestMessage headers to be properly divided between the request headers
// collection and the request content headers collection for all well-known header names. And custom headers
// are only allowed in the request headers collection and not in the request content headers collection.
if (IsWellKnownContentHeader(headerName))
{
if (request.Content == null)
{
// Create empty content so that we can send the entity-body header.
request.Content = new ByteArrayContent(Array.Empty<byte>());
}
request.Content.Headers.TryAddWithoutValidation(headerName, _webHeaderCollection[headerName]);
}
else
{
request.Headers.TryAddWithoutValidation(headerName, _webHeaderCollection[headerName]);
}
}
_sendRequestTask = client.SendAsync(
request,
_allowReadStreamBuffering ? HttpCompletionOption.ResponseContentRead : HttpCompletionOption.ResponseHeadersRead,
_sendRequestCts.Token);
HttpResponseMessage responseMessage = await _sendRequestTask.ConfigureAwait(false);
HttpWebResponse response = new HttpWebResponse(responseMessage, _requestUri, _cookieContainer);
if (!responseMessage.IsSuccessStatusCode)
{
throw new WebException(
SR.Format(SR.net_servererror, (int)response.StatusCode, response.StatusDescription),
null,
WebExceptionStatus.ProtocolError,
response);
}
return response;
}
示例12: ReadElementContentAsBase64Async_Helper
private async Task<int> ReadElementContentAsBase64Async_Helper(Task<bool> task, byte[] buffer, int index, int count)
{
await task.ConfigureAwait(false);
if (!task.Result)
{
return 0;
}
else
{
// setup base64 decoder
InitBase64Decoder();
// read binary data
return await ReadElementContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false);
}
}
示例13: RunConcurrentTask
/// <summary>
/// Run async task
/// </summary>
/// <param name="task">Task operation</param>
/// <param name="taskId">Task id</param>
protected async void RunConcurrentTask(long taskId, Task task)
{
bool initTaskStatus = false;
bool finishedTaskStatus = true;
Interlocked.Increment(ref activeTaskCount);
try
{
TaskStatus.TryAdd(taskId, initTaskStatus);
await task.ConfigureAwait(false);
Interlocked.Increment(ref finishedTaskCount);
}
catch (Exception e)
{
Interlocked.Increment(ref failedTaskCount);
if (OnError != null)
{
TaskExceptionEventArgs eventArgs = new TaskExceptionEventArgs(taskId, e);
try
{
OnError(this, eventArgs);
}
catch(Exception devException)
{
Debug.Fail(devException.Message);
}
}
}
finally
{
TaskStatus.TryUpdate(taskId, finishedTaskStatus, initTaskStatus);
}
Interlocked.Decrement(ref activeTaskCount);
taskCounter.Signal();
RunRemainingTask();
}
示例14: ParseTextAsync_AsyncFunc
private async Task<ValueTuple<int, int, int, bool>> ParseTextAsync_AsyncFunc(Task<ValueTuple<int, int, int, bool>> task)
{
while (true)
{
await task.ConfigureAwait(false);
int outOrChars = _lastParseTextState.outOrChars;
char[] chars = _lastParseTextState.chars;
int pos = _lastParseTextState.pos;
int rcount = _lastParseTextState.rcount;
int rpos = _lastParseTextState.rpos;
int orChars = _lastParseTextState.orChars;
char c = _lastParseTextState.c;
switch (_parseText_NextFunction)
{
case ParseTextFunction.ParseText:
task = ParseTextAsync(outOrChars, chars, pos, rcount, rpos, orChars, c);
break;
case ParseTextFunction.Entity:
task = ParseTextAsync_ParseEntity(outOrChars, chars, pos, rcount, rpos, orChars, c);
break;
case ParseTextFunction.ReadData:
task = ParseTextAsync_ReadData(outOrChars, chars, pos, rcount, rpos, orChars, c);
break;
case ParseTextFunction.Surrogate:
task = ParseTextAsync_Surrogate(outOrChars, chars, pos, rcount, rpos, orChars, c);
break;
case ParseTextFunction.NoValue:
return ParseText_NoValue(outOrChars, pos);
case ParseTextFunction.PartialValue:
return ParseText_PartialValue(pos, rcount, rpos, orChars, c);
}
}
}
示例15: _ParseTextAsync
// Parses text or white space node.
// Returns true if a node has been parsed and its data set to curNode.
// Returns false when a white space has been parsed and ignored (according to current whitespace handling) or when parsing mode is not Full.
// Also returns false if there is no text to be parsed.
private async Task<bool> _ParseTextAsync(Task<ValueTuple<int, int, int, bool>> parseTask)
{
int startPos;
int endPos;
int orChars = 0;
if (parseTask != null)
goto Parse;
// skip over the text if not in full parsing mode
if (_parsingMode != ParsingMode.Full)
{
ValueTuple<int, int, int, bool> tuple_9;
do
{
tuple_9 = await ParseTextAsync(orChars);
startPos = tuple_9.Item1;
endPos = tuple_9.Item2;
orChars = tuple_9.Item3;
} while (!tuple_9.Item4);
goto IgnoredNode;
}
_curNode.SetLineInfo(_ps.LineNo, _ps.LinePos);
Debug.Assert(_stringBuilder.Length == 0);
parseTask = ParseTextAsync(orChars).AsTask();
Parse:
var tuple_10 = await parseTask.ConfigureAwait(false);
startPos = tuple_10.Item1;
endPos = tuple_10.Item2;
orChars = tuple_10.Item3;
if (tuple_10.Item4)
{
if (endPos - startPos == 0)
{
goto IgnoredNode;
}
XmlNodeType nodeType = GetTextNodeType(orChars);
if (nodeType == XmlNodeType.None)
{
goto IgnoredNode;
}
Debug.Assert(endPos - startPos > 0);
_curNode.SetValueNode(nodeType, _ps.chars, startPos, endPos - startPos);
return true;
}
// only piece of the value was returned
else
{
// V1 compatibility mode -> cache the whole value
if (_v1Compat)
{
ValueTuple<int, int, int, bool> tuple_11;
do
{
if (endPos - startPos > 0)
{
_stringBuilder.Append(_ps.chars, startPos, endPos - startPos);
}
tuple_11 = await ParseTextAsync(orChars);
startPos = tuple_11.Item1;
endPos = tuple_11.Item2;
orChars = tuple_11.Item3;
} while (!tuple_11.Item4);
if (endPos - startPos > 0)
{
_stringBuilder.Append(_ps.chars, startPos, endPos - startPos);
}
Debug.Assert(_stringBuilder.Length > 0);
XmlNodeType nodeType = GetTextNodeType(orChars);
if (nodeType == XmlNodeType.None)
{
_stringBuilder.Length = 0;
goto IgnoredNode;
}
_curNode.SetValueNode(nodeType, _stringBuilder.ToString());
_stringBuilder.Length = 0;
return true;
}
// V2 reader -> do not cache the whole value yet, read only up to 4kB to decide whether the value is a whitespace
else
{
bool fullValue = false;
// if it's a partial text value, not a whitespace -> return
if (orChars > 0x20)
//.........这里部分代码省略.........