本文整理汇总了C#中TaskFactory.FromAsync方法的典型用法代码示例。如果您正苦于以下问题:C# TaskFactory.FromAsync方法的具体用法?C# TaskFactory.FromAsync怎么用?C# TaskFactory.FromAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类TaskFactory
的用法示例。
在下文中一共展示了TaskFactory.FromAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: DiscoverAsync
public static async Task<bool> DiscoverAsync(object state = null)
{
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
IPEndPoint endpoint = new IPEndPoint(IPAddress.Broadcast, 1900);
byte[] outBuf = Encoding.ASCII.GetBytes(BroadcastPacket);
byte[] inBuf = new byte[4096];
int tries = MaxTries;
while (--tries > 0)
{
try
{
TaskFactory factory = new TaskFactory();
sock.ReceiveTimeout = DiscoverTimeout;
await factory.FromAsync(sock.BeginSendTo(outBuf, 0, outBuf.Length, 0, endpoint, null, null), end =>
{
sock.EndSendTo(end);
}).ConfigureAwait(false);
var ar = sock.BeginReceive(inBuf, 0, inBuf.Length, 0, null, null);
if (ar == null) throw new Exception("ar is null");
int length = await factory.FromAsync(ar, end => sock.EndReceive(end)).ConfigureAwait(false);
string data = Encoding.ASCII.GetString(inBuf, 0, length).ToLowerInvariant();
var match = ResponseLocation.Match(data);
if (match.Success && match.Groups["location"].Success)
{
System.Diagnostics.Debug.WriteLine("Found UPnP device at " + match.Groups["location"]);
string controlUrl = GetServiceUrl(match.Groups["location"].Value);
if (!string.IsNullOrEmpty(controlUrl))
{
_controlUrl = controlUrl;
System.Diagnostics.Debug.WriteLine("Found control URL at " + _controlUrl);
return true;
}
}
}
catch (Exception ex)
{
// ignore timeout exceptions
if (!(ex is SocketException && ((SocketException) ex).ErrorCode == 10060))
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
}
}
return false;
}
示例2: GetPopularCallback
public async void GetPopularCallback()
{
var request = HttpWebRequest.Create("http://tvseries.apphb.com/RestServiceImpl.svc/json/getSerie/ga") as HttpWebRequest;
var factory = new TaskFactory();
var task = factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);
try
{
var response=await task;
System.IO.Stream responseStream = response.GetResponseStream();
string data;
using (var reader = new System.IO.StreamReader(responseStream))
{
data = reader.ReadToEnd();
}
responseStream.Close();
//MessageBox.Show("Recieved payload of " + data.Length + " characters");
// MessageBox.Show(data);
List<Popular> feed = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Popular>>(data);
PopularSeries.DataContext = feed;
//MessageBox.Show(feed.Count.ToString());
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
示例3: OnNavigatedTo
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
loadingProgressRing.IsActive = true;
try
{
if (Constants.RecUriDic.Count == 0 && Constants.CategoryNameList.Count == 0)
{
try
{
DataServiceQuery<CATEGORY> cateDsq = (DataServiceQuery<CATEGORY>)(from cate in ctx.CATEGORY
select cate);
TaskFactory<IEnumerable<CATEGORY>> tfc = new TaskFactory<IEnumerable<CATEGORY>>();
IEnumerable<CATEGORY> categories = await tfc.FromAsync(cateDsq.BeginExecute(null, null), iar => cateDsq.EndExecute(iar));
foreach (var c in categories)
{
Constants.CategoryNameList.Add(c.CATE_NAME);
}
}
catch
{
ShowMessageDialog("categories!");
}
try
{
DataServiceQuery<RECOMMENDATION> craDsq = (DataServiceQuery<RECOMMENDATION>)(from re in ctx.RECOMMENDATION
select re);
TaskFactory<IEnumerable<RECOMMENDATION>> tf = new TaskFactory<IEnumerable<RECOMMENDATION>>();
IEnumerable<RECOMMENDATION> recommendation = await tf.FromAsync(craDsq.BeginExecute(null, null), iar => craDsq.EndExecute(iar));
foreach (var r in recommendation)
{
Constants.RecUriDic.Add(r.TITLE, r.ICON_URL);
}
}
catch
{
ShowMessageDialog("recommedations!");
}
}
}
catch
{
ShowMessageDialog("On nav to");
}
courseDsq = (DataServiceQuery<COURSE_AVAIL>)(from course_avail in ctx.COURSE_AVAIL select course_avail);
courseDsq.BeginExecute(OnCourseAvailComplete, null);
UserProfileBt.DataContext = Constants.User;
//UserProfileBt.IsEnabled = false;
}
示例4: OnNavigatedTo
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
course = e.Parameter as Course;
globalRate = 0;
attendDsq = (DataServiceQuery<ATTEND>)(from attend in ctx.ATTEND
where attend.COURSE_ID == course.ID && attend.CUSTOMER_ID == Constants.User.ID
select attend);
try
{
TaskFactory<IEnumerable<ATTEND>> tf = new TaskFactory<IEnumerable<ATTEND>>();
IEnumerable<ATTEND> attends = await tf.FromAsync(attendDsq.BeginExecute(null, null), iar => attendDsq.EndExecute(iar));
if (attends.Count() != 0)
{
enterCommentStackPanel.Visibility = Visibility.Visible;
}
}
catch
{
ShowMessageDialog();
}
commentDsq = (DataServiceQuery<COMMENT_DET>)(from comment in ctx.COMMENT_DET
where comment.COURSE_ID == course.ID
orderby comment.TIME ascending
select comment);
commentDsq.BeginExecute(OnCommentComplete, null);
}
示例5: OnNavigatedTo
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
try
{
teachDsq = (DataServiceQuery<COURSE_AVAIL>)(from course in ctx.COURSE_AVAIL
where course.TEACHER_NAME == Constants.User.NAME
select course);
TaskFactory<IEnumerable<COURSE_AVAIL>> tf = new TaskFactory<IEnumerable<COURSE_AVAIL>>();
IEnumerable<COURSE_AVAIL> attends = await tf.FromAsync(ctx.BeginExecute<COURSE_AVAIL>(
new Uri("/GetAllCoursesAttendedByCustomer?customer_id=" + Constants.User.ID, UriKind.Relative), null, null),
iar => ctx.EndExecute<COURSE_AVAIL>(iar));
IEnumerable<COURSE_AVAIL> teaches = await tf.FromAsync(teachDsq.BeginExecute(null, null), iar => teachDsq.EndExecute(iar));
courseData = new StoreData();
foreach (var c in attends)
{
Course tmpCourse = Constants.CourseAvail2Course(c);
tmpCourse.IsBuy = true;
tmpCourse.IsTeach = false;
courseData.AddCourse(tmpCourse);
}
foreach (var c in teaches)
{
Course tmpCourse = Constants.CourseAvail2Course(c);
tmpCourse.IsTeach = true;
tmpCourse.IsBuy = false;
courseData.AddCourse(tmpCourse);
}
dataCategory = courseData.GetGroupsByAttendingOrTeaching();
cvs1.Source = dataCategory;
UserProfileBt.DataContext = Constants.User;
}
catch
{
ShowMessageDialog("on navi to");
}
}
示例6: GetStreamAsync
async Task<Stream> GetStreamAsync(string uri)
{
TaskFactory factory = new TaskFactory();
WebRequest request = WebRequest.Create(uri);
WebResponse response = await factory.FromAsync<WebResponse>(request.BeginGetResponse,
request.EndGetResponse,
null);
return response.GetResponseStream();
}
示例7: SetAttendTeachNumber
public async void SetAttendTeachNumber()
{
try
{
ctx = new CloudEDUEntities(new Uri(Constants.DataServiceURI));
teachDsq = (DataServiceQuery<COURSE_AVAIL>)(from course in ctx.COURSE_AVAIL
where course.TEACHER_NAME == this.NAME
select course);
TaskFactory<IEnumerable<COURSE_AVAIL>> tf = new TaskFactory<IEnumerable<COURSE_AVAIL>>();
IEnumerable<COURSE_AVAIL> attends = await tf.FromAsync(ctx.BeginExecute<COURSE_AVAIL>(
new Uri("/GetAllCoursesAttendedByCustomer?customer_id=" + this.ID, UriKind.Relative), null, null),
iar => ctx.EndExecute<COURSE_AVAIL>(iar));
ATTEND_COUNT = attends.Count();
IEnumerable<COURSE_AVAIL> teaches = await tf.FromAsync(teachDsq.BeginExecute(null, null), iar => teachDsq.EndExecute(iar));
TEACH_COUNT = teaches.Count();
}
catch
{
ShowMessageDialog("Set Attend Teach Number ");
}
}
示例8: ListAllProducts
// Get an entire entity set.
static async void ListAllProducts(ClassLibrary2.ServiceReference1.Container container)
{
var dsQuery = container.Products;
var tf = new TaskFactory<IEnumerable<ClassLibrary2.ServiceReference1.Product>>();
var list = (await tf.FromAsync(dsQuery.BeginExecute(null, null),
iar => dsQuery.EndExecute(iar))).ToList();
foreach (var p in list)
{
DisplayProduct(p);
}
}
示例9: OnNavigatedTo
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
categoryName = e.Parameter as string;
Title.Text = Constants.UpperInitialChar(categoryName);
loadingProgressRing.IsActive = true;
/****** 这里是所有推荐课程的搜索 ***/
if (categoryName.Equals("Recommendation"))
{
TaskFactory<IEnumerable<COURSE_AVAIL>> tfRec = new TaskFactory<IEnumerable<COURSE_AVAIL>>();
IEnumerable<COURSE_AVAIL> recCourses = await tfRec.FromAsync(ctx.BeginExecute<COURSE_AVAIL>(
new Uri("/GetRecommendedCourses?customer_id=" + Constants.User.ID, UriKind.Relative), null, null),
iar => ctx.EndExecute<COURSE_AVAIL>(iar));
categoryCourses = new StoreData();
foreach (var c in recCourses)
{
categoryCourses.AddCourse(Constants.CourseRec2Course(c));
}
dataCategory = categoryCourses.GetSingleGroupByCategoryTitle(categoryName);
cvs1.Source = dataCategory;
loadingProgressRing.IsActive = false;
//courseDsq = (DataServiceQuery<COURSE_AVAIL>)(from course in ctx.COURSE_AVAIL
// where course.ID > 5
// select course);
//courseDsq.BeginExecute(OnRecommendationMannualCoursesComplete, null);
}
else
{
if (Constants.CategoryNameList.Contains(categoryName))
{
courseDsq = (DataServiceQuery<COURSE_AVAIL>)(from course_avail in ctx.COURSE_AVAIL
where course_avail.CATE_NAME == categoryName
select course_avail);
courseDsq.BeginExecute(OnCategoryCoursesComplete, null);
}
else
{
recDsq = (DataServiceQuery<COURSE_RECO_AVAIL>)(from re in ctx.COURSE_RECO_AVAIL
where re.RECO_TITLE == categoryName
select re);
recDsq.BeginExecute(OnRecommendationCoursesComplete, null);
}
}
UserProfileBt.DataContext = Constants.User;
}
示例10: LogoutButton_Click_1
/// <summary>
/// Handles the 1 event of the LogoutButton_Click control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param>
private async void LogoutButton_Click_1(object sender, RoutedEventArgs e)
{
((Frame)Window.Current.Content).Navigate(typeof(Login.LoginSel));
string courseUplaodUri = "/AddDBLog?opr='Logout'&msg='" + Constants.User.NAME + "'";
//ctx.UpdateObject(c);
CloudEDUEntities ctx = new CloudEDUEntities(new Uri(Constants.DataServiceURI));
try
{
TaskFactory<IEnumerable<bool>> tf = new TaskFactory<IEnumerable<bool>>();
IEnumerable<bool> result = await tf.FromAsync(ctx.BeginExecute<bool>(new Uri(courseUplaodUri, UriKind.Relative), null, null), iar => ctx.EndExecute<bool>(iar));
}
catch
{
}
}
示例11: BeginRequest
/// <summary>${WP_mapping_ServiceRequest_method_BeginRequest_Object_D}</summary>
/// <param name="state">${WP_mapping_ServiceRequest_method_BeginRequest_Object_param_state}</param>
public async Task<string> BeginRequest()
{
HttpWebRequest request = HttpWebRequest.CreateHttp(ProxyEncodeUrl(Url));
request.AllowReadStreamBuffering = true;
string uriString = ProxyEncodeUrl(this.Url, this.ProxyUrl);
if (this.RequestMethod==HttpRequestMethod.POST)//REST的POST
{
request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
request.Method = "POST";
byte[] data = Encoding.UTF8.GetBytes(PostBody);
TaskFactory factory = new TaskFactory();
Stream stream = await factory.FromAsync<Stream>(request.BeginGetRequestStream, request.EndGetRequestStream, null);
await stream.WriteAsync(data, 0, data.Length);
stream.Dispose();
}
else
{
request.Method = "GET";
}
try
{
HttpWebResponse response = (HttpWebResponse)await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);
StreamReader reader = new StreamReader(response.GetResponseStream());
string result = await reader.ReadToEndAsync();
reader.Dispose();
return result;
}
catch (WebException ex)
{
if (ex.Response != null)
{
var response = ex.Response as HttpWebResponse;
StreamReader reader = new StreamReader(response.GetResponseStream());
var message = reader.ReadToEnd();
throw new WebException(message, ex.InnerException);
}
else
{
throw ex;
}
}
catch (Exception ex)
{
throw ex;
}
}
示例12: OnNavigatedTo
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
course = e.Parameter as Course;
sharedNoteDsq = (DataServiceQuery<NOTE_AVAIL>)(from selectNote in ctx.NOTE_AVAIL
where selectNote.COURSE_ID == course.ID.Value && selectNote.SHARE == true
orderby selectNote.DATE descending
select selectNote);
switchButton.Content = "Mine";
TaskFactory<IEnumerable<NOTE_AVAIL>> tf = new TaskFactory<IEnumerable<NOTE_AVAIL>>();
IEnumerable<NOTE_AVAIL> nas = await tf.FromAsync(sharedNoteDsq.BeginExecute(null, null), iar => sharedNoteDsq.EndExecute(iar));
sharedNotesList = nas.ToList();
foreach (var n in sharedNotesList)
{
allSharedNotesStackPanel.Children.Add(GenerateSharedNoteItem(n.ID, n.TITLE, n.CONTENT, n.CUSTOMER_NAME, n.DATE, n.LESSON_NUMBER, n.CUSTOMER_ID.Value));
}
}
示例13: ExecuteQuery
private static Task<GoogleMapsQueryResult> ExecuteQuery(Uri queryUri)
{
if (GoogleMapsQueryInMemoryCache.ContainsKey(queryUri.ToString()))
{
return Task.FromResult(new GoogleMapsQueryResult(GoogleMapsQueryInMemoryCache[queryUri.ToString()]));
}
var tf = new TaskFactory();
var httpRequest = WebRequestCreator.GZip.Create(queryUri);
return tf.FromAsync<WebResponse>(httpRequest.BeginGetResponse, httpRequest.EndGetResponse, null).ContinueWith(
asyncResult =>
{
try
{
var httpResponse = asyncResult.Result;
string jsonString;
using (var reader = new System.IO.StreamReader(httpResponse.GetResponseStream()))
{
jsonString = reader.ReadToEnd();
}
var response = JsonConvert.DeserializeObject<DirectionsResult>(jsonString);
if (response.status != null && response.status != "OK")
{
return new GoogleMapsQueryResult(new Exception(string.Format("One or more error were returned by the query: {0}", response.status)));
}
GoogleMapsQueryInMemoryCache.TryAdd(httpRequest.RequestUri.ToString(), response);
return new GoogleMapsQueryResult(response);
}
catch (Exception ex)
{
return new GoogleMapsQueryResult(ex);
}
});
}
示例14: onGetLessonComplete
private async void onGetLessonComplete(IAsyncResult iar)
{
try
{
System.Diagnostics.Debug.WriteLine("get lesson complete");
IEnumerable<LESSON> lessons = dba.lessonDsq.EndExecute(iar);
foreach (var l in lessons)
{
this.allLessons.Add(l);
//coursesData.AddCourse(Constants.CourseAvail2Course(c));
}
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
foreach (var l in this.allLessons)
{
System.Diagnostics.Debug.WriteLine(l.TITLE);
allLessonsStackPanel.Children.Add(GenerateALessonBox(l));
}
//dataCategory = coursesData.GetGroupsByCategory();
//cvs1.Source = dataCategory;
//(SemanticZoom.ZoomedOutView as ListViewBase).ItemsSource = cvs1.View.CollectionGroups;
//loadingProgressRing.IsActive = false;
});
}
catch
{
//ShowMessageDialog();
// Network Connection error.
}
try
{
resourceDic = new Dictionary<string, int>(Constants.ResourceType.Count);
for (int i = 0; i <Constants.ResourceType.Count; ++i)
{
DataServiceQuery<RES_TYPE> dps = (DataServiceQuery<RES_TYPE>)(from res_type in ctx.RES_TYPE
where res_type.DESCRIPTION.Trim() == Constants.ResourceType[i]
select res_type);
TaskFactory<IEnumerable<RES_TYPE>> tf = new TaskFactory<IEnumerable<RES_TYPE>>();
RES_TYPE resID = (await tf.FromAsync(dps.BeginExecute(null, null), result => dps.EndExecute(result))).FirstOrDefault();
resourceDic.Add(Constants.ResourceType[i], resID.ID);
}
}
catch
{
ShowMessageDialog("Network connection error!11");
return;
}
}
示例15: AddImageButton
private async void AddImageButton(int lessonId, StackPanel parent)
{
System.Diagnostics.Debug.WriteLine("AddImageButton!");
DataServiceQuery<RESOURCE> dps = (DataServiceQuery<RESOURCE>)(ctx.RESOURCE.Where(r => r.LESSON_ID == lessonId));
TaskFactory<IEnumerable<RESOURCE>> tf = new TaskFactory<IEnumerable<RESOURCE>>();
IEnumerable<RESOURCE> resources = (await tf.FromAsync(dps.BeginExecute(null, null), iar => dps.EndExecute(iar)));
foreach (var r in resources)
{
System.Diagnostics.Debug.WriteLine(r.URL);
Image image = null;
if (r.TYPE == 2)
{
image = GenerateDocImage(r.URL);
parent.Children.Add(image);
}
else if (r.TYPE == 1)
{
image = GenerateAudioImage(r.URL);
parent.Children.Add(image);
}
else if (r.TYPE == 3)
{
image = GenerateAudioImage(r.URL);
parent.Children.Add(image);
}
image.Tapped += ResImageTapped;
}
}