本文整理汇总了C#中TaskCompletionSource.SetResult方法的典型用法代码示例。如果您正苦于以下问题:C# TaskCompletionSource.SetResult方法的具体用法?C# TaskCompletionSource.SetResult怎么用?C# TaskCompletionSource.SetResult使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类TaskCompletionSource
的用法示例。
在下文中一共展示了TaskCompletionSource.SetResult方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SendReport
public Task<bool> SendReport(IReport report)
{
var tcs = new TaskCompletionSource<bool>();
if (MFMailComposeViewController.CanSendMail)
{
var c = new MFMailComposeViewController();
c.SetSubject(report.Title);
c.SetToRecipients(new[] {_settings.DevelopersEmail});
c.SetMessageBody(report.Body, false);
NSData data = new NSString(report.Attachment).DataUsingEncoding(NSStringEncoding.UTF8);
c.AddAttachmentData(data, "text/xml", "info.xml");
_application.RootController.PresentViewController(c, true, null);
c.Finished += (sender, e) =>
{
tcs.SetResult(e.Result == MFMailComposeResult.Sent);
e.Controller.DismissViewController(true, null);
};
}
else
{
var alert = new UIAlertView("Cannot send report", "E-mail messages not allowed", null, "OK");
alert.Clicked += (sender, args) => tcs.SetResult(false);
alert.Show();
}
return tcs.Task;
}
示例2: OpenEmailManager
public Task OpenEmailManager(string[] emails, string subject, string text, string[] attachments)
{
var tcs = new TaskCompletionSource<bool>();
if (MFMailComposeViewController.CanSendMail)
{
var c = new MFMailComposeViewController();
c.SetToRecipients(emails);
c.SetSubject(subject ?? "");
c.SetMessageBody(text ?? "", false);
foreach (string attachment in attachments)
{
NSData data = NSData.FromFile(attachment);
if (data != null)
c.AddAttachmentData(data, GetMimeType(attachment), Path.GetFileName(attachment));
}
_application.RootController.PresentViewController(c, true, null);
c.Finished += (sender, e) =>
{
tcs.SetResult(e.Result == MFMailComposeResult.Sent);
_application.InvokeOnMainThread(() => e.Controller.DismissViewController(true, null));
};
}
else
{
var alert = new UIAlertView("Cannot send report", "E-mail messages not allowed", null, "OK");
alert.Clicked += (sender, args) => tcs.SetResult(false);
alert.Show();
}
return tcs.Task;
}
示例3: Display
public static Task<string> Display(string title, string text = null)
{
Popup popup = new Popup();
popup.Height = 240;
popup.Width = 480;
popup.VerticalOffset = 100;
popup.VerticalAlignment = VerticalAlignment.Center;
InputDialog dialog = new InputDialog();
dialog.lblTitle.Text = title;
dialog.txtContent.Text = text ?? "";
popup.Child = dialog;
TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();
dialog.btnCancel.Click += (s, ea) =>
{
tcs.SetResult(null);
popup.IsOpen = false;
};
dialog.btnOk.Click += (s, ea) =>
{
tcs.SetResult(dialog.txtContent.Text);
popup.IsOpen = false;
};
popup.IsOpen = true;
return tcs.Task;
}
示例4: PlatformShow
private static Task<string> PlatformShow(string title, string description, string defaultText, bool usePasswordMode)
{
tcs = new TaskCompletionSource<string>();
var keyboardViewController = new KeyboardInputViewController(
title, description, defaultText, usePasswordMode, gameViewController);
UIApplication.SharedApplication.InvokeOnMainThread(delegate
{
gameViewController.PresentViewController(keyboardViewController, true, null);
keyboardViewController.View.InputAccepted += (sender, e) =>
{
gameViewController.DismissViewController(true, null);
if (!tcs.Task.IsCompleted)
tcs.SetResult(keyboardViewController.View.Text);
};
keyboardViewController.View.InputCanceled += (sender, e) =>
{
gameViewController.DismissViewController(true, null);
if (!tcs.Task.IsCompleted)
tcs.SetResult(null);
};
});
return tcs.Task;
}
示例5: DisplayYesNo
public static Task<bool> DisplayYesNo(string text)
{
Popup popup = new Popup();
popup.Height = 240;
popup.Width = 480;
popup.VerticalOffset = 100;
popup.VerticalAlignment = VerticalAlignment.Center;
InputDialog dialog = new InputDialog();
dialog.lblTitle.Text = "Question";
dialog.txtContent.Text = text;
dialog.btnCancel.Content = "No";
dialog.btnOk.Content = "Yes";
popup.Child = dialog;
TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
dialog.btnCancel.Click += (s, ea) =>
{
tcs.SetResult(false);
popup.IsOpen = false;
};
dialog.btnOk.Click += (s, ea) =>
{
tcs.SetResult(true);
popup.IsOpen = false;
};
popup.IsOpen = true;
return tcs.Task;
}
示例6: ContinueWith
public Task ContinueWith(Action<Task> continuationAction)
{
//Console.WriteLine("enter __Task.ContinueWith " + new { this.IsCompleted, continuationAction });
var x = new TaskCompletionSource<object>();
if (this.IsCompleted)
{
continuationAction(this);
x.SetResult(null);
}
else
{
InternalContinueWithAfterIsCompleted +=
delegate
{
if (x == null)
return;
continuationAction(this);
x.SetResult(null);
x = null;
};
}
//Console.WriteLine("exit __Task.ContinueWith " + new { this.IsCompleted, continuationAction });
return x.Task;
}
示例7: Should_call_on_error
public async Task Should_call_on_error()
{
var onErrorCalled = new TaskCompletionSource<ErrorContext>();
OnTestTimeout(() => onErrorCalled.SetResult(null));
await StartPump(context =>
{
// handler enlists a failing transaction enlistment to the DTC transaction which will fail when commiting the transaction.
Transaction.Current.EnlistDurable(EnlistmentWhichFailesDuringPrepare.Id, new EnlistmentWhichFailesDuringPrepare(), EnlistmentOptions.None);
return Task.FromResult(0);
},
context =>
{
onErrorCalled.SetResult(context);
return Task.FromResult(ErrorHandleResult.Handled);
}
,TransportTransactionMode.TransactionScope);
await SendMessage(InputQueueName);
var errorContext = await onErrorCalled.Task;
Assert.IsInstanceOf<TransactionAbortedException>(errorContext.Exception);
// since some transports doesn't have native retry counters we can't expect the attempts to be fully consistent since if
// dispose throws the message might be picked up before the counter is incremented
Assert.LessOrEqual(1, errorContext.ImmediateProcessingFailures);
}
示例8: Should_dispatch_the_message
public async Task Should_dispatch_the_message(TransportTransactionMode transactionMode)
{
var messageReceived = new TaskCompletionSource<bool>();
OnTestTimeout(() => messageReceived.SetResult(false));
await StartPump(
context =>
{
if (context.Headers.ContainsKey("FromOnError"))
{
messageReceived.SetResult(true);
return Task.FromResult(0);
}
throw new Exception("Simulated exception");
},
async context =>
{
await SendMessage(InputQueueName, new Dictionary<string, string> { { "FromOnError", "true" } }, context.TransportTransaction);
return ErrorHandleResult.Handled;
}, transactionMode);
await SendMessage(InputQueueName);
Assert.True(await messageReceived.Task, "Message not dispatched properly");
}
示例9: GetJson
public static async Task<JObject> GetJson(String url)
{
var tcs = new TaskCompletionSource<string>();
var client = new WebClient();
client.DownloadStringCompleted += (s, e) =>
{
if (e.Error == null)
{
tcs.SetResult(e.Result);
}
else
{
tcs.SetResult(null);
}
};
client.DownloadStringAsync(new Uri(url));
return await tcs.Task.ContinueWith<JObject>((task) =>
{
if (task.Result != null)
{
return JObject.Parse(task.Result);
}
else
{
return null;
}
});
}
示例10: OnActivityResult
static int PICK_CONTACT_REQUEST = 42; // The request code
protected void OnActivityResult(TaskCompletionSource<ContactInfo> tcs, ActivityResultEventArgs e) //int requestCode, Android.App.Result resultCode, Intent data)
{
// Check which request it is that we're responding to
if (e.requestCode == PICK_CONTACT_REQUEST)
{
// Make sure the request was successful
if (e.resultCode == Android.App.Result.Ok)
{
var loader = new CursorLoader(MainActivity.Instance, e.data.Data, projection, null, null, null);
var cursor = (Android.Database.ICursor)loader.LoadInBackground();
var contactList = new List<ContactInfo>();
if (cursor.MoveToFirst())
{
do
{
contactList.Add(GetContactInfoFromCursor(cursor));
} while (cursor.MoveToNext());
}
tcs.SetResult(contactList.FirstOrDefault());
return;
}
}
tcs.SetResult(null);
}
示例11: WriteAsync
public static Task WriteAsync(this Stream stream, byte[] buffer, int offset, int count)
{
var tcs = new TaskCompletionSource<object>();
var sr = stream.BeginWrite(buffer, offset, count, ar =>
{
if (ar.CompletedSynchronously)
{
return;
}
try
{
stream.EndWrite(ar);
tcs.SetResult(null);
}
catch (Exception ex)
{
tcs.SetException(ex);
}
}, null);
if (sr.CompletedSynchronously)
{
try
{
stream.EndWrite(sr);
tcs.SetResult(null);
}
catch (Exception ex)
{
tcs.SetException(ex);
}
}
return tcs.Task;
}
示例12: WaitForLoadedAsync
public async static Task<ExceptionRoutedEventArgs> WaitForLoadedAsync(this BitmapImage bitmapImage)
{
var tcs = new TaskCompletionSource<ExceptionRoutedEventArgs>();
// Need to set it to noll so that the compiler does not
// complain about use of unassigned local variable.
RoutedEventHandler reh = null;
ExceptionRoutedEventHandler ereh = null;
reh = (s, e) =>
{
bitmapImage.ImageOpened -= reh;
bitmapImage.ImageFailed -= ereh;
tcs.SetResult(null);
};
ereh = (s, e) =>
{
bitmapImage.ImageOpened -= reh;
bitmapImage.ImageFailed -= ereh;
tcs.SetResult(e);
};
bitmapImage.ImageOpened += reh;
bitmapImage.ImageFailed += ereh;
return await tcs.Task;
}
示例13: DiscoverAddress
public Task<DiscoveryResult> DiscoverAddress(string webAPI)
{
var completionSource = new TaskCompletionSource<DiscoveryResult>();
var baseUri = new Uri(webAPI, UriKind.Absolute);
var requestUri = new Uri(baseUri, "rsd.xml");
var rsdFileRequest = webRequestFactory.Create(requestUri);
// Kick off the async discovery workflow
rsdFileRequest.GetResponseAsync()
.ContinueWith<DiscoveryResult>(ProcessRsdResponse)
.ContinueWith(c =>
{
if (c.Result.Success)
completionSource.SetResult(c.Result);
else
{
Trace.WriteLine(string.Format(
"Rsd.xml does not exist, trying to discover via link. Error was {0}", c.Result.FailMessage), "INFO");
DiscoverRsdLink(webAPI)
.ContinueWith(t => completionSource.SetResult(t.Result));
}
});
return completionSource.Task;
}
示例14: ReadFromStreamAsync
/// <summary>
/// Asynchronously deserializes an object of the specified type.
/// </summary>
/// <param name="type">The type of the object to deserialize.</param>
/// <param name="readStream">The <see cref="T:System.IO.Stream" /> to read.</param>
/// <param name="content">The <see cref="T:System.Net.Http.HttpContent" />, if available. It may be null.</param>
/// <param name="formatterLogger">The <see cref="T:System.Net.Http.Formatting.IFormatterLogger" /> to log events to.</param>
/// <returns>
/// A <see cref="T:System.Threading.Tasks.Task" /> whose result will be an object of the given type.
/// </returns>
public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, System.Net.Http.HttpContent content, IFormatterLogger formatterLogger)
{
var tcs = new TaskCompletionSource<object>();
try
{
var reader = GetJsonReader(readStream);
using (reader)
{
var jsonSerializerSettings = new JsonSerializerSettings();
jsonSerializerSettings.Converters.Add(new HyperNewtonsoftJsonConverter());
var jsonSerializer = JsonSerializer.Create(jsonSerializerSettings);
var output = jsonSerializer.Deserialize(reader, type);
if (formatterLogger != null)
{
jsonSerializer.Error += (sender, e) =>
{
var exception = e.ErrorContext.Error;
formatterLogger.LogError(e.ErrorContext.Path, exception.Message);
e.ErrorContext.Handled = true;
};
}
tcs.SetResult(output);
}
}
catch (Exception e)
{
if (formatterLogger == null) throw;
formatterLogger.LogError(String.Empty, e.Message);
tcs.SetResult(GetDefaultValueForType(type));
}
return tcs.Task;
}
示例15: LoadAreasCache
public static Task LoadAreasCache()
{
var task = new TaskCompletionSource<bool>();
if (CMS.Cache.Areas == null)
{
CMS.Cache.Areas = new ObservableCollection<Area>();
var cee = new CmsWebServiceClient(Utils.WcfBinding, Utils.WcfEndPoint);
DateTime now = DateTime.Now;
System.Diagnostics.Debug.WriteLine("LoadAreasCache First {0}", now.ToString("G"));
//AREAS
cee.GetAreasCompleted += (s1, e1) =>
{
CMS.Cache.Areas = new ObservableCollection<Area>(e1.Result.OrderBy(x => x.AreaNumber));
var elapsed = DateTime.Now - now;
System.Diagnostics.Debug.WriteLine("LoadAreasCache: {0}", elapsed.TotalSeconds);
task.SetResult(true);
};
cee.GetAreasAsync();
}
else
{
System.Diagnostics.Debug.WriteLine("-----------------------------------------------------------");
System.Diagnostics.Debug.WriteLine("LoadAreasCache: ALREADY LOADED !!!");
System.Diagnostics.Debug.WriteLine("-----------------------------------------------------------");
task.SetResult(true);
return task.Task; //Already loaded
}
return task.Task;
}