AsyncTask检测是否完成(AsyncTask detecting if done)
我创建了一个AsyncTask,当我执行它时从网站加载数据。 目前,我得到一个空指针异常,我认为是因为我想太早填充UI,所以我希望创建一些if语句,说如果AsyncTask没有完成显示加载图形和填充数据的时间。 但我不确定如何去做这件事,是否有人知道我该如何实现这一目标,或者至少让我朝正确的方向发展。
这是我的代码到目前为止
public void checkPreferences(){ SharedPreferences preferences = getSharedPreferences("prefs", Context.MODE_PRIVATE); ChosenMethod = preferences.getString("ChosenMethod", ChosenMethod); ChosenLeagueID = preferences.getString("ChosenLeagueId", ChosenLeagueID); ChosenTeamId = preferences.getString("ChosenTeamId", ChosenTeamId); Log.v("lc", "newsurl" + newsFeedURL); Log.v("myapp", "ChosenMethod Home = " + ChosenMethod); Log.v("myapp", "ChosenLeagueID Home = " + ChosenLeagueID); Log.v("myapp", "ChosenTeamID Home = " + ChosenTeamId); if (ChosenMethod.equals("Team")) { setContentView(R.layout.homeactteam2); newsAmount = 5; } else { newsAmount = 10; setContentView(R.layout.homeactteam); } } @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); //Check Preferences which sets UI checkPreferences(); PostTask posttask; posttask = new PostTask(); posttask.execute(); FillData(); Button backbtn = (Button) findViewById(R.id.backbtn); //Listening to button event backbtn.setOnClickListener(new View.OnClickListener() { public void onClick(View arg0) { //Starting a new Intent Intent previousScreen = new Intent(getApplicationContext(), ChooseTeamActivity.class); ChosenMethod = "null"; SharedPreferences preferences = getSharedPreferences("prefs", Context.MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.putString("ChosenMethod", ChosenMethod); editor.commit(); previousScreen.putExtra("FullData", fulldata); startActivity(previousScreen); } }); //((PullToRefreshListView) getListView()).setOnRefreshListener(new OnRefreshListener() { // // public void onRefresh() { // // Do work to refresh the list here. // loadData(); // } //}); // } public void loadNewsFeed(){ newsFeedRequest = "website/" + chosenLeagueId + "/news?timestamp=" + unixTimeStamp; newsFeedURL = "https://www.website.com" + newsFeedRequest; String myhash = buildHmacSignature(apiKey, newsFeedURL); HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(newsFeedURL); List<NameValuePair> pairs = new ArrayList<NameValuePair>(); pairs.add(new BasicNameValuePair("requestToken", myhash)); pairs.add(new BasicNameValuePair("apiUser", apiUser)); try { post.setEntity (new UrlEncodedFormEntity(pairs)); HttpResponse response = client.execute(post); BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); String json = reader.readLine(); fulldata = String.valueOf(json); Log.v("myApp","newsdata" + fulldata); newsList = new ArrayList<String>(); newsList2 = new ArrayList<String>(); newsList3 = new ArrayList<String>(); imageList = new ArrayList<String>(); JSONObject obj = new JSONObject(json); JSONObject objData = obj.getJSONObject("data"); JSONArray jArray = objData.getJSONArray("news"); Log.v("lc","newsAmount= " + newsAmount); for(int t = 0; t < newsAmount; t++){ JSONObject newsTitleDict = jArray.getJSONObject(t); imageList.add(newsTitleDict.getString("image_small")); newsList3.add(newsTitleDict.getString("title")); } for(int t = 0; t < 1; t++){ JSONObject newsTitleDict = jArray.getJSONObject(t); newsList.add(newsTitleDict.getString("title")); // newsList2.add(newsTitleDict.getString("title")); } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void loadResultsFeed(){ resultsFeedRequest = "website/" + chosenLeagueId + "/results?&team_id=" + ChosenTeamId + "&limit=31×tamp=" + unixTimeStamp; resultsFeedURL = "https://www.website.com" + resultsFeedRequest; String myhash = buildHmacSignature(apiKey, resultsFeedURL); HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(resultsFeedURL); List<NameValuePair> pairs = new ArrayList<NameValuePair>(); pairs.add(new BasicNameValuePair("requestToken", myhash)); pairs.add(new BasicNameValuePair("apiUser", apiUser)); try { post.setEntity (new UrlEncodedFormEntity(pairs)); HttpResponse response = client.execute(post); BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); String json = reader.readLine(); fulldata = String.valueOf(json); Log.v("myApp","resultsdata" + fulldata); newsList = new ArrayList<String>(); newsList2 = new ArrayList<String>(); newsList3 = new ArrayList<String>(); imageList = new ArrayList<String>(); JSONObject obj = new JSONObject(json); JSONObject objData = obj.getJSONObject("data"); JSONArray jArray = objData.getJSONArray("results"); if(jArray.length() < 1) loadLastResults(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void loadLastResults(){ resultsFeedRequest = "website/" + chosenLeagueId + "/results?month=04&team_id=" + ChosenTeamId + "&limit=31×tamp=" + unixTimeStamp; resultsFeedURL = "https://www.website.com" + resultsFeedRequest; String myhash = buildHmacSignature(apiKey, resultsFeedURL); Date anotherCurDate = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("MM"); String CurMonth = formatter.format(anotherCurDate); int Int = Integer.parseInt(CurMonth); int MonthInt = Int -1; CurMonth = (String) (String.valueOf(MonthInt)); if (CurMonth.equals("1")){ lastMonth = "12"; } else { if(CurMonth.length() < 2){ lastMonth = "0" + CurMonth; } else { lastMonth = CurMonth; } } Log.v("lc","month= " + CurMonth); Log.v("lc","LastMonth= " + lastMonth); HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(resultsFeedURL); List<NameValuePair> pairs = new ArrayList<NameValuePair>(); pairs.add(new BasicNameValuePair("requestToken", myhash)); pairs.add(new BasicNameValuePair("apiUser", apiUser)); try { post.setEntity (new UrlEncodedFormEntity(pairs)); HttpResponse response = client.execute(post); BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); String json = reader.readLine(); fulldata = String.valueOf(json); Log.v("myApp","resultsdata" + fulldata); newsList = new ArrayList<String>(); newsList2 = new ArrayList<String>(); newsList3 = new ArrayList<String>(); imageList = new ArrayList&t;String>(); JSONObject obj = new JSONObject(json); JSONObject objData = obj.getJSONObject("data"); JSONArray jArray = objData.getJSONArray("results"); for(int t = 0; t < 1; t++){ resultsDict = jArray.getJSONObject(t); HomeTeam = resultsDict.getString("hometeam"); AwayTeam = resultsDict.getString("awayteam"); HomeScore = resultsDict.getString("homescore"); AwayScore = resultsDict.getString("awayscore"); Attendance = resultsDict.getString("attendance"); Division = resultsDict.getString("division"); Log.v("lc","hometeam" + HomeTeam); Log.v("lc","awayteam" + AwayTeam); } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public class PostTask extends AsyncTask<Void, String, Boolean> { @Override protected Boolean doInBackground(Void... params) { boolean result = false; loadNewsFeed(); loadResultsFeed(); loadLastResults(); publishProgress("progress"); return result; } protected void onProgressUpdate(String... progress) { StringBuilder str = new StringBuilder(); for (int i = 1; i < progress.length; i++) { str.append(progress[i] + " "); } } } public void FillData(){ if (ChosenMethod.equals("Team")) { resultsView = LayoutInflater.from(getBaseContext()).inflate(R.layout.resultscell, null); TextView homeTeam = (TextView) resultsView.findViewById(R.id.HomeTeam); homeTeam.setText(HomeTeam); TextView awayTeam = (TextView) resultsView.findViewById(R.id.AwayTeam); awayTeam.setText(AwayTeam); TextView homeScore = (TextView) resultsView.findViewById(R.id.HomeScore); homeScore.setText(HomeScore); TextView awayScore = (TextView) resultsView.findViewById(R.id.AwayScore); awayScore.setText(AwayScore); TextView attendance = (TextView) resultsView.findViewById(R.id.Attendence); attendance.setText("Att:" + Attendance); TextView division = (TextView) resultsView.findViewById(R.id.Division); division.setText(Division); arrayAdapter = new ArrayAdapter<String>(this, R.layout.single_item, newsList); String[] mStrings = (String[]) imageList.toArray(new String[imageList.size()]); String[] news = (String[]) newsList3.toArray(new String[newsList3.size()]); arrayAdapter3 = new LazyAdapter(this, mStrings, news); ListView list = getListView(); list.setTextFilterEnabled(true); LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE ); View header = inflater.inflate( R.layout.homeheader, list, false); View header2 = inflater.inflate( R.layout.homeheader2, list, false); View header3 = inflater.inflate( R.layout.homeheader3, list, false); //setListAdapter (arrayAdapter); adapter = new MergeAdapter(); adapter.addView(header); adapter.addAdapter(arrayAdapter); adapter.addView(header2); adapter.addView(resultsView); adapter.addView(header3); adapter.addAdapter(arrayAdapter3); setListAdapter(adapter); } else { arrayAdapter = new ArrayAdapter<String>(this, R.layout.single_item, newsList); arrayAdapter2 = new ArrayAdapter<String>(this, R.layout.single_item, newsList2); //arrayAdapter3 = new ArrayAdapter(this, R.layout.complex_item, newsList3); String[] mStrings = (String[]) imageList.toArray(new String[imageList.size()]); String[] news = (String[]) newsList3.toArray(new String[newsList3.size()]); arrayAdapter3 = new LazyAdapter(this, mStrings, news); ListView list = getListView(); list.setTextFilterEnabled(true); LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE ); View header3 = inflater.inflate( R.layout.homeheader3, list, false); //setListAdapter (arrayAdapter); adapter = new MergeAdapter(); adapter.addView(header3); adapter.addAdapter(arrayAdapter3); setListAdapter(adapter); } }
I have created an AsyncTask that loads data from a website then when I execute it. At the moment I'm getting a null pointer exception which I think is caused because I'm trying to fill the UI too early so I'm hoping to create some kind of if statement that says if AsyncTask isn't complete show a loading graphic and when it is fill the data. But I'm not sure how to go about doing this does anyone know how I could achieve this or at least point me in the right direction.
Here's my code so far
public void checkPreferences(){ SharedPreferences preferences = getSharedPreferences("prefs", Context.MODE_PRIVATE); ChosenMethod = preferences.getString("ChosenMethod", ChosenMethod); ChosenLeagueID = preferences.getString("ChosenLeagueId", ChosenLeagueID); ChosenTeamId = preferences.getString("ChosenTeamId", ChosenTeamId); Log.v("lc", "newsurl" + newsFeedURL); Log.v("myapp", "ChosenMethod Home = " + ChosenMethod); Log.v("myapp", "ChosenLeagueID Home = " + ChosenLeagueID); Log.v("myapp", "ChosenTeamID Home = " + ChosenTeamId); if (ChosenMethod.equals("Team")) { setContentView(R.layout.homeactteam2); newsAmount = 5; } else { newsAmount = 10; setContentView(R.layout.homeactteam); } } @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); //Check Preferences which sets UI checkPreferences(); PostTask posttask; posttask = new PostTask(); posttask.execute(); FillData(); Button backbtn = (Button) findViewById(R.id.backbtn); //Listening to button event backbtn.setOnClickListener(new View.OnClickListener() { public void onClick(View arg0) { //Starting a new Intent Intent previousScreen = new Intent(getApplicationContext(), ChooseTeamActivity.class); ChosenMethod = "null"; SharedPreferences preferences = getSharedPreferences("prefs", Context.MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.putString("ChosenMethod", ChosenMethod); editor.commit(); previousScreen.putExtra("FullData", fulldata); startActivity(previousScreen); } }); //((PullToRefreshListView) getListView()).setOnRefreshListener(new OnRefreshListener() { // // public void onRefresh() { // // Do work to refresh the list here. // loadData(); // } //}); // } public void loadNewsFeed(){ newsFeedRequest = "website/" + chosenLeagueId + "/news?timestamp=" + unixTimeStamp; newsFeedURL = "https://www.website.com" + newsFeedRequest; String myhash = buildHmacSignature(apiKey, newsFeedURL); HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(newsFeedURL); List<NameValuePair> pairs = new ArrayList<NameValuePair>(); pairs.add(new BasicNameValuePair("requestToken", myhash)); pairs.add(new BasicNameValuePair("apiUser", apiUser)); try { post.setEntity (new UrlEncodedFormEntity(pairs)); HttpResponse response = client.execute(post); BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); String json = reader.readLine(); fulldata = String.valueOf(json); Log.v("myApp","newsdata" + fulldata); newsList = new ArrayList<String>(); newsList2 = new ArrayList<String>(); newsList3 = new ArrayList<String>(); imageList = new ArrayList<String>(); JSONObject obj = new JSONObject(json); JSONObject objData = obj.getJSONObject("data"); JSONArray jArray = objData.getJSONArray("news"); Log.v("lc","newsAmount= " + newsAmount); for(int t = 0; t < newsAmount; t++){ JSONObject newsTitleDict = jArray.getJSONObject(t); imageList.add(newsTitleDict.getString("image_small")); newsList3.add(newsTitleDict.getString("title")); } for(int t = 0; t < 1; t++){ JSONObject newsTitleDict = jArray.getJSONObject(t); newsList.add(newsTitleDict.getString("title")); // newsList2.add(newsTitleDict.getString("title")); } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void loadResultsFeed(){ resultsFeedRequest = "website/" + chosenLeagueId + "/results?&team_id=" + ChosenTeamId + "&limit=31×tamp=" + unixTimeStamp; resultsFeedURL = "https://www.website.com" + resultsFeedRequest; String myhash = buildHmacSignature(apiKey, resultsFeedURL); HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(resultsFeedURL); List<NameValuePair> pairs = new ArrayList<NameValuePair>(); pairs.add(new BasicNameValuePair("requestToken", myhash)); pairs.add(new BasicNameValuePair("apiUser", apiUser)); try { post.setEntity (new UrlEncodedFormEntity(pairs)); HttpResponse response = client.execute(post); BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); String json = reader.readLine(); fulldata = String.valueOf(json); Log.v("myApp","resultsdata" + fulldata); newsList = new ArrayList<String>(); newsList2 = new ArrayList<String>(); newsList3 = new ArrayList<String>(); imageList = new ArrayList<String>(); JSONObject obj = new JSONObject(json); JSONObject objData = obj.getJSONObject("data"); JSONArray jArray = objData.getJSONArray("results"); if(jArray.length() < 1) loadLastResults(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void loadLastResults(){ resultsFeedRequest = "website/" + chosenLeagueId + "/results?month=04&team_id=" + ChosenTeamId + "&limit=31×tamp=" + unixTimeStamp; resultsFeedURL = "https://www.website.com" + resultsFeedRequest; String myhash = buildHmacSignature(apiKey, resultsFeedURL); Date anotherCurDate = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("MM"); String CurMonth = formatter.format(anotherCurDate); int Int = Integer.parseInt(CurMonth); int MonthInt = Int -1; CurMonth = (String) (String.valueOf(MonthInt)); if (CurMonth.equals("1")){ lastMonth = "12"; } else { if(CurMonth.length() < 2){ lastMonth = "0" + CurMonth; } else { lastMonth = CurMonth; } } Log.v("lc","month= " + CurMonth); Log.v("lc","LastMonth= " + lastMonth); HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(resultsFeedURL); List<NameValuePair> pairs = new ArrayList<NameValuePair>(); pairs.add(new BasicNameValuePair("requestToken", myhash)); pairs.add(new BasicNameValuePair("apiUser", apiUser)); try { post.setEntity (new UrlEncodedFormEntity(pairs)); HttpResponse response = client.execute(post); BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); String json = reader.readLine(); fulldata = String.valueOf(json); Log.v("myApp","resultsdata" + fulldata); newsList = new ArrayList<String>(); newsList2 = new ArrayList<String>(); newsList3 = new ArrayList<String>(); imageList = new ArrayList<String>(); JSONObject obj = new JSONObject(json); JSONObject objData = obj.getJSONObject("data"); JSONArray jArray = objData.getJSONArray("results"); for(int t = 0; t < 1; t++){ resultsDict = jArray.getJSONObject(t); HomeTeam = resultsDict.getString("hometeam"); AwayTeam = resultsDict.getString("awayteam"); HomeScore = resultsDict.getString("homescore"); AwayScore = resultsDict.getString("awayscore"); Attendance = resultsDict.getString("attendance"); Division = resultsDict.getString("division"); Log.v("lc","hometeam" + HomeTeam); Log.v("lc","awayteam" + AwayTeam); } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public class PostTask extends AsyncTask<Void, String, Boolean> { @Override protected Boolean doInBackground(Void... params) { boolean result = false; loadNewsFeed(); loadResultsFeed(); loadLastResults(); publishProgress("progress"); return result; } protected void onProgressUpdate(String... progress) { StringBuilder str = new StringBuilder(); for (int i = 1; i < progress.length; i++) { str.append(progress[i] + " "); } } } public void FillData(){ if (ChosenMethod.equals("Team")) { resultsView = LayoutInflater.from(getBaseContext()).inflate(R.layout.resultscell, null); TextView homeTeam = (TextView) resultsView.findViewById(R.id.HomeTeam); homeTeam.setText(HomeTeam); TextView awayTeam = (TextView) resultsView.findViewById(R.id.AwayTeam); awayTeam.setText(AwayTeam); TextView homeScore = (TextView) resultsView.findViewById(R.id.HomeScore); homeScore.setText(HomeScore); TextView awayScore = (TextView) resultsView.findViewById(R.id.AwayScore); awayScore.setText(AwayScore); TextView attendance = (TextView) resultsView.findViewById(R.id.Attendence); attendance.setText("Att:" + Attendance); TextView division = (TextView) resultsView.findViewById(R.id.Division); division.setText(Division); arrayAdapter = new ArrayAdapter<String>(this, R.layout.single_item, newsList); String[] mStrings = (String[]) imageList.toArray(new String[imageList.size()]); String[] news = (String[]) newsList3.toArray(new String[newsList3.size()]); arrayAdapter3 = new LazyAdapter(this, mStrings, news); ListView list = getListView(); list.setTextFilterEnabled(true); LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE ); View header = inflater.inflate( R.layout.homeheader, list, false); View header2 = inflater.inflate( R.layout.homeheader2, list, false); View header3 = inflater.inflate( R.layout.homeheader3, list, false); //setListAdapter (arrayAdapter); adapter = new MergeAdapter(); adapter.addView(header); adapter.addAdapter(arrayAdapter); adapter.addView(header2); adapter.addView(resultsView); adapter.addView(header3); adapter.addAdapter(arrayAdapter3); setListAdapter(adapter); } else { arrayAdapter = new ArrayAdapter<String>(this, R.layout.single_item, newsList); arrayAdapter2 = new ArrayAdapter<String>(this, R.layout.single_item, newsList2); //arrayAdapter3 = new ArrayAdapter(this, R.layout.complex_item, newsList3); String[] mStrings = (String[]) imageList.toArray(new String[imageList.size()]); String[] news = (String[]) newsList3.toArray(new String[newsList3.size()]); arrayAdapter3 = new LazyAdapter(this, mStrings, news); ListView list = getListView(); list.setTextFilterEnabled(true); LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE ); View header3 = inflater.inflate( R.layout.homeheader3, list, false); //setListAdapter (arrayAdapter); adapter = new MergeAdapter(); adapter.addView(header3); adapter.addAdapter(arrayAdapter3); setListAdapter(adapter); } }
原文:https://stackoverflow.com/questions/10946499
最满意答案
好的,我自己找到了解决方案。 这里的问题是关于竞争条件 - 一个事件试图停止计数(这意味着引发另一个事件)然后再次启动它(这是有问题的,因为我的功能(我猜)已经混乱了第一个,可能是第二个事件甚至没有添加到事件检测队列中)。 如果我的解释错了,我会感激一些批评;)
这是两个修改过的函数,它们正确地解决了线程管理。 关键是让其他事件完成他们的工作,直到我得到理想的状态。
当我想关闭计数时,我让应用程序从队列中执行事件,直到两个线程都不忙('while'循环):
private: void turnOffAcquisition() { if (counting_paused) return; if (plot_bgworker->IsBusy) plot_bgworker->CancelAsync(); if (data_bgworker->IsBusy) data_bgworker->CancelAsync(); while((plot_bgworker->IsBusy) || (data_bgworker->IsBusy)) // Continue to process events until both workers stop working Application::DoEvents(); // Then, you can process another thread requests! :) label_timer->Enabled = false; counting_paused = true; }
类似地,当我想重新开始计数时,我让应用程序执行事件,直到我检查两个线程都忙(再次,'while'循环):
private: void turnOnAcquisition() { if (!counting_paused) return; if (!plot_bgworker->IsBusy) plot_bgworker->RunWorkerAsync(); if (!data_bgworker->IsBusy) data_bgworker->RunWorkerAsync(); while((!plot_bgworker->IsBusy) || (!data_bgworker->IsBusy)) // Continue to process events until both workers start working Application::DoEvents(); // Then, you can process another thread requests! :) label_timer->Enabled = true; counting_paused = false; }
Ok, I found the solution by myself. The problem here was about the race condition - one event tried to stop counting (which meant raising another event) and then starting it again (which was problematic, as my function (I guess) was already cluttered with the first one and probably the second event wasn't even added to the event detected queue). If I am wrong with the explanation, I would appreciate some criticism down there ;)
Here are two modified functions, which solved thread management correctly. The key was to let the other events do their work until I get desired state.
When I want to turn off counting, I let the applications do the events from the queue until both threads will not be busy (the 'while' loop):
private: void turnOffAcquisition() { if (counting_paused) return; if (plot_bgworker->IsBusy) plot_bgworker->CancelAsync(); if (data_bgworker->IsBusy) data_bgworker->CancelAsync(); while((plot_bgworker->IsBusy) || (data_bgworker->IsBusy)) // Continue to process events until both workers stop working Application::DoEvents(); // Then, you can process another thread requests! :) label_timer->Enabled = false; counting_paused = true; }
Similarily, when I want to restart counting, I let the application do the events until I check that both threads are busy (again, the 'while' loop):
private: void turnOnAcquisition() { if (!counting_paused) return; if (!plot_bgworker->IsBusy) plot_bgworker->RunWorkerAsync(); if (!data_bgworker->IsBusy) data_bgworker->RunWorkerAsync(); while((!plot_bgworker->IsBusy) || (!data_bgworker->IsBusy)) // Continue to process events until both workers start working Application::DoEvents(); // Then, you can process another thread requests! :) label_timer->Enabled = true; counting_paused = false; }
相关问答
更多-
是的,.so文件需要安装到PKGLIBDIR中。 你可以通过运行“pg_config”找出PKGLIBDIR是什么。 例如,在带有PostgreSQL 9.4的Ubuntu系统上,pg_config将返回: PKGLIBDIR = /usr/lib/postgresql/9.4/lib 此外,worker_spi - 1.0.sql应安装到SHAREDIR / extension中。 在带有PostgreSQL 9.4的Ubuntu系统上,从pg_config返回的SHAREDIR是: SHAREDIR = ...
-
1.添加以下使用方法: using System.ComponentModel; 背景工作者 : private readonly BackgroundWorker worker = new BackgroundWorker(); 3.订阅事件: worker.DoWork += worker_DoWork; worker.RunWorkerCompleted += worker_RunWorkerCompleted; 实现两种方法: private void worker_DoWork(object ...
-
在进度页面中执行背景 如果您需要传递(并返回)一个对象,请在Progress ctor中执行此操作 private void click(object sender, RoutedEventArgs e) { Progress progressDialog = new Progress(); progressDialog.Show(); if (progressDialog != null) progressDialog = null; } namespace BackGround ...
-
线程和后台工作者(Threading and Background Worker)[2022-03-16]
您无法在非UI线程上更新GUI控件,因此您必须在循环期间尝试“报告”调查结果。 在这里,我只使用ListBox中的字符串副本启动线程: bgw.RunWorkerAsync(ListBox1.Items.Cast(Of String)) 我们需要一个简单的类来报告信息: Public Class UserStatus Property Name As String Property Kind As Integer End Class 然后在DoWork方法中 Private Sub bgw_Do ... -
好的,我自己找到了解决方案。 这里的问题是关于竞争条件 - 一个事件试图停止计数(这意味着引发另一个事件)然后再次启动它(这是有问题的,因为我的功能(我猜)已经混乱了第一个,可能是第二个事件甚至没有添加到事件检测队列中)。 如果我的解释错了,我会感激一些批评;) 这是两个修改过的函数,它们正确地解决了线程管理。 关键是让其他事件完成他们的工作,直到我得到理想的状态。 当我想关闭计数时,我让应用程序从队列中执行事件,直到两个线程都不忙('while'循环): private: void turnOffAcqu ...
-
后台工作者同步(Background worker synchronization)[2022-09-13]
您遇到的问题是经典的生产者 - 消费者问题。 请查看http://en.wikipedia.org/wiki/Producer-consumer_problem 一个简单的解释是你将有两个线程。 一个是生产者(GUID生成者),另一个是消费者。 您将通过使用信号量使这些线程保持同步。 信号量将负责在队列满时停止生产者,并在消费者为空时停止消费者。 这个过程在维基百科的文章中得到了很好的解释,我打赌你可以在互联网上找到c#中Producer-Consumer的基本实现。 The problem you hav ... -
我认为你得到错误,因为在USP_Select_Registration内部你试图从表单控件中读取值。 这是由另一个线程创建的。 RunWorkComleted在创建Backgroundworker的同一个线程中执行,这就是代码P_Panel.Visible = False将正常执行的原因。 但是DoWork在另一个线程上执行。 当您尝试访问某些表单控件以读取值时 TXT_Search.Text - 它引发错误 您可以将搜索参数传递给BackgroundWorker ,但需要向USP_Select_Regis ...
-
AutoResetEvent + Background Worker相互结合(AutoResetEvent + Background Worker conjunction with each other)[2019-11-22]
在DoWork()我调用AutoResetEvent.WaitOne() 。 这是否会在调用AutoResetEvent.Set()之前停止当前线程? 例如,如果从不调用AutoResetEvent.Set() , Background Worker只是暂停而不执行任何操作? 从MSDN WaitHandle.WaitOne Method引用的答案是肯定的: 阻止当前线程,直到当前WaitHandle收到信号。 编辑 :对于您添加的代码,while循环将等待Set() within DoWork() I c ... -
要扩展@ LarsTech的注释,您当前的进度计算甚至不依赖于j因此将ReportProgress调用移到内部循环之外。 这将通过减少调用次数来帮助响应,甚至不会改变ProgressBar的行为。 for (int i = 0; i < x; ++i) //Parallel.For(0, x, i => { bw.ReportProgress((int)(((double)i / (double)y + (double)1 / (double)x) * 100)); ...
-
使用后台工作进程时,Windows应用程序被挂起(Windows Application gets hanged when using a background worker process)[2020-04-06]
如果您不希望在等待长进程时挂起UI,则必须使用线程。 BackgroundWorker是一个很好的实现,它提供了用于报告进度的钩子,允许用户中止进程等。 关于Stack Overflow的BackgroundWorker有很多问题,或者查看MSDN文档 。 If you don't want your UI to hang while waiting for long processes you have to use a thread. BackgroundWorker is a good impleme ...