本文整理汇总了C#中Promise类的典型用法代码示例。如果您正苦于以下问题:C# Promise类的具体用法?C# Promise怎么用?C# Promise使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Promise类属于命名空间,在下文中一共展示了Promise类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: TestFailure
public void TestFailure()
{
Promise<long> p = new Promise<long>(cb => cb("uh oh", default(long)));
bool test = false;
p.Success(x => test = true);
Assert.IsFalse(test);
p.Fail(s => test = true);
Assert.IsTrue(test);
var p2 = p.FlatMap(l => new Promise<int>(cb => cb(null, 3)));
test = false;
p2.Success(x => test = true);
Assert.IsFalse(test);
p2.Fail(s => test = true);
Assert.IsTrue(test);
}
示例2: UIRenderPlane
public UIRenderPlane(UISpriteBatch batch, Promise<Texture2D> texture)
{
this.GD = batch.GraphicsDevice;
this.Target = batch.GetBuffer();
this.Texture = texture;
this.Batch = batch;
//GD.PresentationParameters.RenderTargetUsage = RenderTargetUsage.PreserveContents;
/** Switch the render target **/
Batch.Pause();
GD.SetRenderTarget(0, Target);
GD.Clear(Color.TransparentBlack);
Batch.Resume();
/**
batch.Pause();
var buffer = batch.GetBuffer();
var gd = GameFacade.GraphicsDevice;
var renderTarget = gd.GetRenderTarget(0);
gd.SetRenderTarget(0, buffer);
batch.Resume();
gd.render
//gd.Clear(Color.TransparentBlack);**/
}
示例3: ShouldAssociateGodfather
public void ShouldAssociateGodfather(Cloud cloud)
{
Login2NewUsers(cloud, (gamer1, gamer2) => {
// Expects godchild event
Promise restOfTheTestCompleted = new Promise();
gamer1.StartEventLoop();
gamer1.Godfather.OnGotGodchild += (GotGodchildEvent e) => {
Assert(e.Gamer.GamerId == gamer2.GamerId, "Should come from player2");
Assert((object)e.Reward == (object)Bundle.Empty, "No reward should be associated");
restOfTheTestCompleted.Done(CompleteTest);
};
// P1 generates a code and associates P2 with it
gamer1.Godfather.GenerateCode()
// Use code
.ExpectSuccess(genCode => gamer2.Godfather.UseCode(genCode))
.ExpectSuccess(dummy => gamer2.Godfather.GetGodfather())
.ExpectSuccess(result => {
Assert(result.GamerId == gamer1.GamerId, "P1 should be godfather");
Assert(result.AsBundle().Root.Has("godfather"), "Underlying structure should be accessible");
return gamer1.Godfather.GetGodchildren();
})
.ExpectSuccess(result => {
Assert(result.Count == 1, "Should have only one godchildren");
Assert(result[0].GamerId == gamer2.GamerId, "P2 should be godchildren");
restOfTheTestCompleted.Resolve();
});
});
}
示例4: ShouldAddFriend
public void ShouldAddFriend(Cloud cloud)
{
// Use two test accounts
Login2NewUsers(cloud, (gamer1, gamer2) => {
// Expects friend status change event
Promise restOfTheTestCompleted = new Promise();
gamer1.StartEventLoop();
gamer1.Community.OnFriendStatusChange += (FriendStatusChangeEvent e) => {
Assert(e.FriendId == gamer2.GamerId, "Should come from P2");
Assert(e.NewStatus == FriendRelationshipStatus.Add, "Should have added me");
restOfTheTestCompleted.Done(CompleteTest);
};
// Add gamer1 as a friend of gamer2
gamer2.Community.AddFriend(gamer1.GamerId)
.ExpectSuccess(addResult => {
// Then list the friends of gamer1, gamer2 should be in it
return gamer1.Community.ListFriends();
})
.ExpectSuccess(friends => {
Assert(friends.Count == 1, "Expects one friend");
Assert(friends[0].GamerId == gamer2.GamerId, "Wrong friend ID");
restOfTheTestCompleted.Resolve();
});
});
}
示例5: BuidlListHal
private object BuidlListHal(Promise<int> total, IEnumerable<Place> places, SearchPlacesParameters parameters)
{
var totalPages = total/parameters.PageSize;
var builder = new HalBuilder(Request.Url.ToString())
.AddProperty("pages", totalPages)
.AddProperty("page", parameters.Page)
.EmbedListResourceWithProperties(
"places",
places,
place => Settings.ToAbsolute(string.Format("/places/{0}", place.Id)),
place => place.Id,
place => place.EnglishName,
place => place.CornishName,
place => place.Type,
place => place.Parish);
if (parameters.Page < totalPages)
builder.AddLink("next", new SearchUrlBuilder(parameters).NextPage().Build());
if (parameters.Page > 1)
builder.AddLink("prev", new SearchUrlBuilder(parameters).PreviousPage().Build());
return builder.Build();
}
示例6: SignIn
public Promise SignIn(string domain, string username, string password)
{
Promise promise = new Promise();
try
{
Uri serverUri = new Uri(appSettings.ServerURI, UriKind.RelativeOrAbsolute);
Uri restUri = new Uri(serverUri, "rest/");
StudentRepository repo = new StudentRepository(restUri);
if (repo == null)
{
throw new Exception("StudentRepository is not initialized.");
}
repo.SignIn(domain, username, password, (StudentRepository.Response response) =>
{
if (response.Success)
{
Token = Guid.NewGuid().ToString();
promise.Resolve(response.Item);
}
else
{
promise.Reject(new Exception(response.Error));
}
});
}
catch (Exception e)
{
promise.Reject(e);
}
return promise;
}
示例7: LoadSettings
public Promise LoadSettings(string studentId)
{
Promise promise = new Promise();
try
{
Uri serverUri = new Uri(appSettings.ServerURI, UriKind.RelativeOrAbsolute);
Uri restUri = new Uri(serverUri, "rest/");
CourseSettingsRepository repo = new CourseSettingsRepository(restUri);
if (repo == null)
{
throw new Exception("CourseSettingsRepository is not initialized.");
}
repo.GetByKey("studentid/", studentId, (CourseSettingsRepository.Response response) =>
{
if (response.Success)
{
promise.Resolve(response.Item);
}
else
{
promise.Reject(new Exception(response.Error));
}
});
}
catch (Exception e)
{
promise.Reject(e);
}
return promise;
}
示例8: Download
/// <summary>
/// Download text from a URL.
/// A promise is returned that is resolved when the download has completed.
/// The promise is rejected if an error occurs during download.
/// </summary>
static IPromise<string> Download(string url)
{
Console.WriteLine("Downloading " + url + " ...");
var promise = new Promise<string>();
using (var client = new WebClient())
{
client.DownloadStringCompleted +=
(s, ev) =>
{
if (ev.Error != null)
{
Console.WriteLine("An error occurred... rejecting the promise.");
// Error during download, reject the promise.
promise.Reject(ev.Error);
}
else
{
Console.WriteLine("... Download completed.");
// Downloaded completed successfully, resolve the promise.
promise.Resolve(ev.Result);
}
};
client.DownloadStringAsync(new Uri(url), null);
}
return promise;
}
示例9: LoadActivityStates
public Promise LoadActivityStates(string studentId, IEnumerable<string> activityIds)
{
Promise promise = new Promise();
try
{
Uri serverUri = new Uri(appSettings.ServerURI, UriKind.RelativeOrAbsolute);
Uri restUri = new Uri(serverUri, "rest/");
ActivityStateRepository repo = new ActivityStateRepository(restUri);
if (repo == null)
{
throw new Exception("ActivityStateRepository is not initialized.");
}
repo.GetActivityStates(studentId, activityIds, (ActivityStateRepository.Response response) =>
{
if (response.Success)
{
promise.Resolve(response.Items);
}
else
{
promise.Reject(new Exception(response.Error));
}
});
}
catch (Exception e)
{
promise.Reject(e);
}
return promise;
}
示例10: _if_onRejected_is_not_a_function_it_must_be_ignored_1
public void _if_onRejected_is_not_a_function_it_must_be_ignored_1()
{
var promise = new Promise<object>();
var resultPromise = promise
.Then(
v => Promise.Resolved(),
null
);
var resolved = 0;
var errors = 0;
var e = new Exception();
resultPromise.Then(() => ++resolved);
resultPromise.Catch(ex =>
{
Assert.Equal(e, ex);
++errors;
});
promise.Reject(e);
Assert.Equal(0, resolved);
Assert.Equal(1, errors);
}
示例11: Promise_Reject_UserInfo
public void Promise_Reject_UserInfo()
{
var args = default(object[]);
var are = new AutoResetEvent(false);
var resolve = new MockCallback(_ => { });
var reject = new MockCallback(a =>
{
args = a;
are.Set();
});
var promise = new Promise(resolve, reject);
var code = "42";
var message = "foo";
var e = new Exception();
e.Data.Add("qux", "baz");
promise.Reject(code, message, e);
are.WaitOne();
Assert.IsNotNull(args);
Assert.AreEqual(1, args.Length);
var json = args[0] as JObject;
Assert.IsNotNull(json);
var userInfo = json["userInfo"] as JObject;
Assert.IsNotNull(userInfo);
Assert.AreEqual("baz", userInfo["qux"]);
}
示例12: lock
// Callback from native code
void IStore.GetInformationAboutProducts_Done(string message)
{
// Extract promise and allow again
Promise<List<ProductInfo>> promise;
lock (this) {
promise = LastGetInformationAboutProductsPromise;
LastGetInformationAboutProductsPromise = null;
}
if (promise == null) {
Debug.LogWarning("Responding to GetInformationAboutProducts without having promise set");
}
Bundle json = Bundle.FromJson(message);
// Error
if (json.Has("error")) {
promise.Reject(ParseError(json));
return;
}
List<ProductInfo> result = new List<ProductInfo>();
foreach (Bundle obj in json["products"].AsArray()) {
result.Add(new ProductInfo(obj));
}
promise.Resolve(result);
}
示例13: AsyncStreamWriter
public AsyncStreamWriter(Stream stream, Action onComplete, Action<Exception> onError)
{
_stream = stream;
_promise = new Promise<bool>();
if (onComplete != null) _promise.Done(r => onComplete());
if (onError != null) _promise.Fail(onError);
}
示例14: GetJsonString
public IPromise<string> GetJsonString()
{
var promise = new Promise<string> ();
using (var client = new WebClient())
{
if (this.headers != null) {
foreach(KeyValuePair<string, string> h in this.headers){
client.Headers.Add(h.Key, h.Value);
}
}
client.DownloadStringCompleted +=
(s, ev) =>
{
if (ev.Error != null){
promise.Reject(ev.Error);
} else {
promise.Resolve(ev.Result);
}
};
client.DownloadStringAsync(new Uri(this.url), null);
}
return promise;
}
示例15: GET
public IPromise<string> GET(Dictionary<string, string> parameters)
{
if (parameters == null) {
throw new ArgumentNullException ();
}
var promise = new Promise<string> ();
using(var client = new WebClient()){
if (this.headers != null) {
foreach(KeyValuePair<string, string> h in this.headers){
client.Headers.Add(h.Key, h.Value);
}
}
client.DownloadStringCompleted +=
(s, ev) =>
{
if (ev.Error != null){
promise.Reject(ev.Error);
} else {
promise.Resolve(ev.Result);
}
};
client.DownloadStringAsync(new Uri(this.url + "?" + PromisedRequest.Helpers.GenerateQueryString(parameters)), null);
}
return promise;
}