C# 从OnCreate重写方法启动异步方法时出现问题 OnCreate()中的) 新线程(新线程开始(()=>{ this.RunOnUiThread(异步()=> { 等待设置数据(今天); //等待FindNotesForDay(今天,今天。添加天数(+6)); 进步。解散(); }); })).Start(); 专用异步任务SetData(日期时间日期) { 等待任务。运行(()=> { dicMyMap=null; dicMyMap=新字典(); 列表组=新列表(); 集团。添加(“星期一”); 集团。添加(“星期二”); 集团。添加(“星期三”); 集团。添加(“星期四”); 集团。添加(“星期五”); 添加(组[0],列表填充(date.ToString(“yyyy-MM-dd”,CultureInfo.InvariantCulture)); 日期=日期加天数(+1); 添加(组[1],列表填充(date.ToString(“yyyy-MM-dd”,CultureInfo.InvariantCulture)); 日期=日期加天数(+1); 添加(组[2],列表填充(date.ToString(“yyyy-MM-dd”,CultureInfo.InvariantCulture)); 日期=日期加天数(+1); 添加(组[3],列表填充(date.ToString(“yyyy-MM-dd”,CultureInfo.InvariantCulture)); 日期=日期加天数(+1); 添加(组[4],列表填充(date.ToString(“yyyy-MM-dd”,CultureInfo.InvariantCulture)); myAdapater=新的ExpandableListViewAdapter(此、组、dicMyMap); SetAdapter(myAdapater); }); } 私有列表列表填充(字符串日期) { string sql=“SELECT*FROM”使用(组)加入groupConvert,其中StartDate='“+date+”,court='“+User.court+”,Year='“+User.IntakeYear+”;”; 列表温度=新列表(); //插入标题 临时添加(新的ClassInstance(“开始时间”、“结束时间”、“主题”、“位置”、“位置”); 使用(MySqlCommand cmd=newmysqlcommand(sql,Connect.GetConnection())) { MySqlDataReader=cmd.ExecuteReader(); while(reader.Read()) { ClassInstance c=新ClassInstance(读卡器[“开始时间”].ToString(),读卡器[“结束时间”].ToString(),读卡器[“主题”].ToString(),读卡器[“位置”].ToString(),读卡器[“基本”].ToString(),读卡器[“注释”].ToString()); 温度添加(c); } } 如果(临时计数==1) { 温度清除(); 临时添加(新ClassInstance(“无类”、“无类”、“无类”、“无类”、“无类”、“无类”)); } 返回温度; }
你好 我目前正试图从AWS上托管的数据库填充ListView。正如您所想象的,加载需要一点时间。我的问题是我当前的代码抛出了一个错误。抛出的错误模棱两可,仅表示程序已崩溃,没有帮助 本质上,我想做的非常简单,我基本上只想在加载这些方法时显示一个对话框 任何关于我的代码的建议都是非常好的 编辑:我已经将错误消息缩小到代码的这个区域。在尝试使用线程之前,我能够加载此活动,但是由于没有加载消息,用户会觉得该活动已冻结,而不是正在加载 谢谢,C# 从OnCreate重写方法启动异步方法时出现问题 OnCreate()中的) 新线程(新线程开始(()=>{ this.RunOnUiThread(异步()=> { 等待设置数据(今天); //等待FindNotesForDay(今天,今天。添加天数(+6)); 进步。解散(); }); })).Start(); 专用异步任务SetData(日期时间日期) { 等待任务。运行(()=> { dicMyMap=null; dicMyMap=新字典(); 列表组=新列表(); 集团。添加(“星期一”); 集团。添加(“星期二”); 集团。添加(“星期三”); 集团。添加(“星期四”); 集团。添加(“星期五”); 添加(组[0],列表填充(date.ToString(“yyyy-MM-dd”,CultureInfo.InvariantCulture)); 日期=日期加天数(+1); 添加(组[1],列表填充(date.ToString(“yyyy-MM-dd”,CultureInfo.InvariantCulture)); 日期=日期加天数(+1); 添加(组[2],列表填充(date.ToString(“yyyy-MM-dd”,CultureInfo.InvariantCulture)); 日期=日期加天数(+1); 添加(组[3],列表填充(date.ToString(“yyyy-MM-dd”,CultureInfo.InvariantCulture)); 日期=日期加天数(+1); 添加(组[4],列表填充(date.ToString(“yyyy-MM-dd”,CultureInfo.InvariantCulture)); myAdapater=新的ExpandableListViewAdapter(此、组、dicMyMap); SetAdapter(myAdapater); }); } 私有列表列表填充(字符串日期) { string sql=“SELECT*FROM”使用(组)加入groupConvert,其中StartDate='“+date+”,court='“+User.court+”,Year='“+User.IntakeYear+”;”; 列表温度=新列表(); //插入标题 临时添加(新的ClassInstance(“开始时间”、“结束时间”、“主题”、“位置”、“位置”); 使用(MySqlCommand cmd=newmysqlcommand(sql,Connect.GetConnection())) { MySqlDataReader=cmd.ExecuteReader(); while(reader.Read()) { ClassInstance c=新ClassInstance(读卡器[“开始时间”].ToString(),读卡器[“结束时间”].ToString(),读卡器[“主题”].ToString(),读卡器[“位置”].ToString(),读卡器[“基本”].ToString(),读卡器[“注释”].ToString()); 温度添加(c); } } 如果(临时计数==1) { 温度清除(); 临时添加(新ClassInstance(“无类”、“无类”、“无类”、“无类”、“无类”、“无类”)); } 返回温度; },c#,multithreading,asynchronous,xamarin,C#,Multithreading,Asynchronous,Xamarin,你好 我目前正试图从AWS上托管的数据库填充ListView。正如您所想象的,加载需要一点时间。我的问题是我当前的代码抛出了一个错误。抛出的错误模棱两可,仅表示程序已崩溃,没有帮助 本质上,我想做的非常简单,我基本上只想在加载这些方法时显示一个对话框 任何关于我的代码的建议都是非常好的 编辑:我已经将错误消息缩小到代码的这个区域。在尝试使用线程之前,我能够加载此活动,但是由于没有加载消息,用户会觉得该活动已冻结,而不是正在加载 谢谢, Joe因此我设法修复了上面的代码以正确运行 如果您有任何反馈
Joe因此我设法修复了上面的代码以正确运行 如果您有任何反馈或意见,请让我知道,我希望有人觉得这有帮助 我完全错误地使用了异步方法,您也无法从oncreate调用异步方法,我相信您已经知道了。我的解决方案的一部分是将我错误地使异步的所有方法改回void(这意味着它们是同步的) 然后我创建了一个线程来运行这些命令,现在它们最终以正确的顺序运行:) 重要的是要注意,在线程中,任何受UI影响的元素都需要使用主UI线程运行,这同样适用于它们调用的方法 下面是我为解决问题而创建的代码区域
Within OnCreate()
new Thread(new ThreadStart(() => {
this.RunOnUiThread(async () =>
{
await SetData(TodaysDate); ;
//await FindNotesForDay(TodaysDate, TodaysDate.AddDays(+6));
progress.Dismiss();
});
})).Start();
private async Task SetData(DateTime date)
{
await Task.Run(() =>
{
dicMyMap = null;
dicMyMap = new Dictionary<string, List<ClassInstance>>();
List<string> group = new List<string>();
group.Add("Monday");
group.Add("Tuesday");
group.Add("Wednesday");
group.Add("Thursday");
group.Add("Friday");
dicMyMap.Add(group[0], ListsPopulation(date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)));
date = date.AddDays(+1);
dicMyMap.Add(group[1], ListsPopulation(date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)));
date = date.AddDays(+1);
dicMyMap.Add(group[2], ListsPopulation(date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)));
date = date.AddDays(+1);
dicMyMap.Add(group[3], ListsPopulation(date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)));
date = date.AddDays(+1);
dicMyMap.Add(group[4], ListsPopulation(date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)));
myAdapater = new ExpandableListViewAdapter(this, group, dicMyMap);
expandableListView.SetAdapter(myAdapater);
});
}
private List<ClassInstance> ListsPopulation(String date)
{
string sql = "SELECT * FROM lectures join groupConvert using (Groups) where StartDate = '" + date + "' AND Cohort = '" + User.Cohort + "' AND Year = '" + User.IntakeYear + "';";
List<ClassInstance> Temp = new List<ClassInstance>();
//Insert Header
Temp.Add(new ClassInstance("Start Time", "End Time", "Subject", "Location", "", ""));
using (MySqlCommand cmd = new MySqlCommand(sql, Connect.GetConnection()))
{
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
ClassInstance c = new ClassInstance(reader["StartTime"].ToString(), reader["EndTime"].ToString(), reader["Theme"].ToString(), reader["Location"].ToString(), reader["Essential"].ToString(), reader["Notes"].ToString());
Temp.Add(c);
}
}
if (Temp.Count == 1)
{
Temp.Clear();
Temp.Add(new ClassInstance("No Classes", "", "", "", "", ""));
}
return Temp;
}
下面是我的完整课程,供其他用户参考。我还没有记录这段代码,因为它在这个评论中足够大
// Try catch attempt to catch all errors, the error dialog thrown within
//the catch is fairly simple
try
{
//Start loading spinner
var LoadingProgressDialog = ProgressDialog.Show(this, "Loading", "Loading", false);
//Start loading thread, this thread will carry out the functions
// in the order you requested
Thread LoadingThread = new Thread(() =>
{
//Line below only relevant to my code
StartMonday.Text = "Week Commencing On " + TodaysDate.ToLongDateString();
// Call this method first
SetData(TodaysDate);
// call this method second
FindNotesForWeek(TodaysDate, 7);
//Update the UI on the main thread but call third this will close the loading dialog message
RunOnUiThread(() => LoadingProgressDialog.Hide());
// End of thread
});
//Run the thread
LoadingThread.Start();
}
catch (Exception e)
{
var ErrorMessageDialog = ProgressDialog.Show(this, "Loading", e.ToString(), false);
}
命名空间MedicalHubaApplication
{
[活动(Label=“时间表”,NoHistory=true)]
公开课时间表:活动
{
ClassInstance populateClass=新ClassInstance();
UserInstance User=new UserInstance();
GetConnectionClass Connect=新建GetConnectionClass();
字典dicMyMap;
TextView DateHeaderTV;
TextView NoteHeaderTV;
可扩展列表视图适配器myAdapater;
ExpandableListView ExpandableListView;
//需要列表的实例
NotesListViewAdapter MyNoteAdapter;
列表视图注释列表视图;
滚动视图滚动视图列表;
TextView StartMonday;
按钮选择日期按钮;
创建时受保护的覆盖无效(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
//在此处创建应用程序
SetContentView(Resource.Layout.timeline);
expandableListView=FindViewById(Resource.Id.ListViewExpanded);
StartMonday=FindViewById(Resource.Id.TextViewStartDateMonday);
SelectDateButton=FindViewById(Resource.Id.SelectDateButton);
NotesListView=FindViewById(Resource.Id.NotesListView);
DateHeaderTV=FindViewById(Resource.Id.DateHeader);
NoteHeaderTV=FindViewById(Resource.Id.NoteHeader);
ScrollViewList=FindViewById(Resource.Id.ScrollView);
//填充用户
User=JsonConvert.DeserializeObject(Intent.GetStringExtra(“用户”);
//星期一
DateTime TodaysDate=DateTime.Now;
而(TodaysDate.DayOfWeek!=DayOfWeek.Monday)今天
namespace MedicalHubApplication
{
[Activity(Label = "TimeTable", NoHistory = true)]
public class TimeTable : Activity
{
ClassInstance populateClass = new ClassInstance();
UserInstance User = new UserInstance();
GetConnectionClass Connect = new GetConnectionClass();
Dictionary<string, List<ClassInstance>> dicMyMap;
TextView DateHeaderTV;
TextView NoteHeaderTV;
ExpandableListViewAdapter myAdapater;
ExpandableListView expandableListView;
// Need Instance of List
NotesListViewAdapter myNoteAdapater;
ListView NotesListView;
ScrollView ScrollViewList;
TextView StartMonday;
Button SelectDateButton;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Create your application here
SetContentView(Resource.Layout.TimeTable);
expandableListView = FindViewById<ExpandableListView>(Resource.Id.ListViewExpanded);
StartMonday = FindViewById<TextView>(Resource.Id.TextViewStartDateMonday);
SelectDateButton = FindViewById<Button>(Resource.Id.SelectDateButton);
NotesListView = FindViewById<ListView>(Resource.Id.NotesListView);
DateHeaderTV = FindViewById<TextView>(Resource.Id.DateHeader);
NoteHeaderTV = FindViewById<TextView>(Resource.Id.NoteHeader);
ScrollViewList = FindViewById<ScrollView>(Resource.Id.ScrollView);
// Populate User
User = JsonConvert.DeserializeObject<UserInstance>(Intent.GetStringExtra("User"));
//Find Monday
DateTime TodaysDate = DateTime.Now;
while (TodaysDate.DayOfWeek != DayOfWeek.Monday) TodaysDate = TodaysDate.AddDays(-1);
try
{
var LoadingProgressDialog = ProgressDialog.Show(this, "Loading", "Loading", false);
Thread LoadingThread = new Thread(() =>
{
StartMonday.Text = "Week Commencing On " + TodaysDate.ToLongDateString();
SetData(TodaysDate);
FindNotesForWeek(TodaysDate, 7);
RunOnUiThread(() => LoadingProgressDialog.Hide());
});
LoadingThread.Start();
}
catch (Exception e)
{
var ErrorMessageDialog = ProgressDialog.Show(this, "Loading", e.ToString(), false);
}
SelectDateButton.Click += delegate
{
DateSelectOnClick();
};
}
private void DateSelectOnClick()
{
DatePickerFragment frag = DatePickerFragment.NewInstance(delegate (DateTime SelectedDate)
{
while (SelectedDate.DayOfWeek != DayOfWeek.Monday) SelectedDate = SelectedDate.AddDays(-1);
try
{
var LoadingProgressDialog = ProgressDialog.Show(this, "Loading", "Loading", false);
Thread LoadingThread = new Thread(() =>
{
RunOnUiThread(() => StartMonday.Text = "Week Commencing On " + SelectedDate.ToLongDateString());
SetData(SelectedDate);
FindNotesForWeek(SelectedDate, 7);
RunOnUiThread(() => LoadingProgressDialog.Hide());
});
LoadingThread.Start();
}
catch (Exception e)
{
var ErrorMessageDialog = ProgressDialog.Show(this, "Loading", e.ToString(), false);
}
});
frag.Show(FragmentManager, DatePickerFragment.TAG);
}
private void SetData(DateTime date)
{
dicMyMap = null;
dicMyMap = new Dictionary<string, List<ClassInstance>>();
List<string> group = new List<string>();
group.Add("Monday");
group.Add("Tuesday");
group.Add("Wednesday");
group.Add("Thursday");
group.Add("Friday");
dicMyMap.Add(group[0], ListsPopulation(date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)));
date = date.AddDays(+1);
dicMyMap.Add(group[1], ListsPopulation(date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)));
date = date.AddDays(+1);
dicMyMap.Add(group[2], ListsPopulation(date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)));
date = date.AddDays(+1);
dicMyMap.Add(group[3], ListsPopulation(date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)));
date = date.AddDays(+1);
dicMyMap.Add(group[4], ListsPopulation(date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)));
myAdapater = new ExpandableListViewAdapter(this, group, dicMyMap);
RunOnUiThread(() => expandableListView.SetAdapter(myAdapater));
}
private List<ClassInstance> ListsPopulation(String date)
{
string sql = "SELECT * FROM lectures join groupConvert using (Groups) where StartDate = '" + date + "' AND Cohort = '" + User.Cohort + "' AND Year = '" + User.IntakeYear + "';";
List<ClassInstance> Temp = new List<ClassInstance>();
//Insert Header
Temp.Add(new ClassInstance("Start Time", "End Time", "Subject", "Location", "", ""));
using (MySqlCommand cmd = new MySqlCommand(sql, Connect.GetConnection()))
{
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
ClassInstance c = new ClassInstance(reader["StartTime"].ToString(), reader["EndTime"].ToString(), reader["Theme"].ToString(), reader["Location"].ToString(), reader["Essential"].ToString(), reader["Notes"].ToString());
Temp.Add(c);
}
}
if (Temp.Count == 1)
{
Temp.Clear();
Temp.Add(new ClassInstance("No Classes", "", "", "", "", ""));
}
return Temp;
}
private void FindNotesForWeek(DateTime StartDate, int DaysInMonth)
{
List<NotesInstance> WeekNotes = new List<NotesInstance>();
WeekNotes.AddRange(FindNotesForDay(StartDate, StartDate.AddDays(+DaysInMonth)));
if (WeekNotes.Count != 0)
{
RunOnUiThread(() => NoteHeaderTV.Visibility = ViewStates.Visible);
RunOnUiThread(() => NotesListView.Visibility = ViewStates.Visible);
RunOnUiThread(() => DateHeaderTV.Text = "Date:");
myNoteAdapater = new NotesListViewAdapter(this, WeekNotes);
RunOnUiThread(() => NotesListView.Adapter = myNoteAdapater);
}
else
{
RunOnUiThread(() => NoteHeaderTV.Visibility = ViewStates.Invisible);
RunOnUiThread(() => NotesListView.Visibility = ViewStates.Invisible);
RunOnUiThread(() => DateHeaderTV.Text = "No Notifications");
}
// Set up Adapter
myNoteAdapater = new NotesListViewAdapter(this, WeekNotes);
RunOnUiThread(() => NotesListView.Adapter = myNoteAdapater);
}
private List<NotesInstance> FindNotesForDay(DateTime StartDate, DateTime EndDate)
{
string sql = "SELECT * FROM Notes WHERE dates between '" + StartDate.ToString("yyyy-MM-dd") + "' AND '" + EndDate.ToString("yyyy-MM-dd") + "' AND yearGroup = '" + User.IntakeYear.ToString() + "';";
List<NotesInstance> Temp = new List<NotesInstance>();
using (MySqlCommand cmd = new MySqlCommand(sql, Connect.GetConnection()))
{
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
NotesInstance c = new NotesInstance(reader.GetDateTime("dates").ToString("dd-MM-yyyy"), reader["Notes"].ToString());
Temp.Add(c);
}
}
return Temp;
}
}