关于BackgroundWorker多线程同步问题

定义了一组 List bgws = new List();其中每一个bgws[i]的DoWork事件做的工作都是一样的,但是有两个参数随每个bgws[i]不同而不同,所以就如下分别写了很多DoWork0、DoWork1.。。。之类的来进行同步处理,有没有更简洁的办法,可以同时调用进行使用?
private void btnCopy_Click(object sender, EventArgs e)
{
for (int i = 0; i < srctable.Count; i++)
{
BackgroundWorker bgw = new BackgroundWorker();
bgws.Add(bgw);
bgws[i].WorkerReportsProgress = true;
bgws[i].WorkerSupportsCancellation = true;
//bgws[i].DoWork += new DoWorkEventHandler(DoWork);
//bgws[i].ProgressChanged += new ProgressChangedEventHandler(UpdateProgress);
//bgws[i].RunWorkerCompleted += new RunWorkerCompletedEventHandler(CompletedWork);
}
string[,] tName = new string[srctable.Count, 2];
//List tName = new List();
for (int i = 0; i < srctable.Count; i++)
{
tName[i, 0] = srctable[i];
tName[i, 1] = destable[i];

        }

        bgws[0].DoWork += new DoWorkEventHandler(DoWork0);
        bgws[0].ProgressChanged += new ProgressChangedEventHandler(UpdateProgress0);
        bgws[0].RunWorkerCompleted += new RunWorkerCompletedEventHandler(CompletedWork0);

        bgws[1].DoWork += new DoWorkEventHandler(DoWork1);
        bgws[1].ProgressChanged += new ProgressChangedEventHandler(UpdateProgress1);
        bgws[1].RunWorkerCompleted += new RunWorkerCompletedEventHandler(CompletedWork1);

        bgws[2].DoWork += new DoWorkEventHandler(DoWork2);
        bgws[2].ProgressChanged += new ProgressChangedEventHandler(UpdateProgress2);
        bgws[2].RunWorkerCompleted += new RunWorkerCompletedEventHandler(CompletedWork2);

        bgws[3].DoWork += new DoWorkEventHandler(DoWork3);
        bgws[3].ProgressChanged += new ProgressChangedEventHandler(UpdateProgress3);
        bgws[3].RunWorkerCompleted += new RunWorkerCompletedEventHandler(CompletedWork3);


        bgws[0].RunWorkerAsync();
        bgws[1].RunWorkerAsync();
        bgws[2].RunWorkerAsync();
        bgws[3].RunWorkerAsync();         
    }
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
关于BackGroundWorker的问题
各位好:rn 第一次用backgroundworker,遇到点问题。我在rn private void backgroundWorker1_DoWork(object sender, rn DoWorkEventArgs e)rn rn // Get the BackgroundWorker that raised this event.rn BackgroundWorker worker = sender as BackgroundWorker;rnrn e.Result = ComputeFibonacci((int)e.Argument, worker, e);rn rn //对DataSet进行的一些操作rn .........................................rn rn 函数中要把一个DaSEt进行整理,同时还要不断的更新进度条?怎样做到呀?在上面这个函数中如何实现?rn e.Result = ComputeFibonacci((int)e.Argument, worker, e);rn 和 //对DataSet进行的一些操作,怎样做到我在整理过程中不断的更新进度条?
一个关于BackgroundWorker 的问题
如何判断一个正在运行的操作被用户停止
【求助】关于BackgroundWorker的问题
我有一个程序,使用了2个BackgroundWorker,2个BackgroundWorker的RunWorkerCompleted均提示正常完成。可当我使用ALT+TAB或执行界面上的Button事件时,界面就白屏假死,任务管理器显示未响应,我实在找不出问题出在那里。先求教各位大神找错思路。rn计算机是新装的系统,且更换过多台计算机,均是这样,肯定不是操作系统的问题。rn代码约有1500行,不能全贴上来。我也不知道贴什么上来可以找出错误。先求个思路。
关于backgroundworker的问题
我在一个form下使用一下backgroundworker.用代理可以实现为本form中的treeview更新数据但是却不能为操作另一个form上的控件,请高手赐教!谢谢 !
关于backgroundWorker的问题
我希望点击一个按钮执行一个后台任务,同时希望,该任务未结束前,按钮事件不要重入。rnrn//按钮事件rnrnprivate void button1_Click(object sender, EventArgs e)rn rn this.backgroundWorker.RunWorkerAsync();rnrn while (this.backgroundWorker.IsBusy)rn rn System.Diagnostics.Debug.WriteLine("this.backgroundWorker.IsBusy");rn System.Threading.Thread.Sleep(1000);rn rn rnrn//后台任务,仅0.1秒执行完毕rnrn private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)rn rn System.Threading.Thread.Sleep(100);rn System.Diagnostics.Debug.WriteLine("backgroundWorker_DoWork complete");rn rnrn程序运行后,输出窗口显示:backgroundWorker_DoWork completernrn但一直输出:this.backgroundWorker.IsBusy,程序进入死锁状态。rnrn
关于backgroundWorker的问题,求救!
我有一个DataGridView绑定了一个DataTable.使用.NET自带的BackGroundWorker往DataTable中插入数据,用BackGroundWorker中ProgressChanged向前台报告插入进度.rn前台接收到DataTable的行数增加后,刷新DataGridView,代码如下:rn private void UpdateProgress(object sender, int percent)rn rn rn dgResult.Refresh();rn this.Invalidate(true);rn progressBar1.Visible = true;rn //label12.Text = string.Format("read 0%...", percent);rn if (percent >= 0 && percent <= 100)rn rn progressBar1.Value = percent;rn rn elsern rn progressBar1.Value = 0;rn rn rn在调试时能得到想要的状态,即DataTable增加一行,DataGridView也增加一行,界面刷新正常,但数据超过一屏,DataGridView需要显示滚动条时,此时界面无反应,数据有插入DataTable,把窗口最小化,再最大化后,看不到的数据能显示出来.rn在Release时,当数据超过一屏时,程序出现死机状态,即DataTable的数据没有再插入,界面也无响应.rn不知是什么原因?rn
关于backgroundworker
今天我想修正一下自己的登陆界面,因为原来的单线程程序登陆窗口在数据库关闭的情况下会像死了一样。。呆上三十秒才有反应,出现连接失败提示。rn我看了看主要是SqlConnection的Open方法,当连接不上的时候,好像一直停在这里不动了。改超时加个计时器对它都不管用。。rn我查找到backgroundworker这个组件可以独立线程运行一个耗时方法,所以试着用了,可是不行。我不大会用。rn能否给我演示一下怎么在它的dowork办法里连接数据库,而超过7秒后提示连接超时。rn或者有没有什么办法可以强制把Open取消呀?rn
关于smp下的多线程同步问题
Java代码如下,问一下,running的话,这样可以进行同步吗?现在的情况是,在SMP环境下,有时running的值不会减到0,在synchronized (running)里面打印出两个一样的running值。rnrnpublic class Spider implements Runnable rnrn private Integer totalThread = 5;rnrn private Integer running = 0;rnrn public void start() rn quit = false;rnrn for (int i = 0; i < totalThread; i++) rn Thread t = new Thread(this, "Spider-Thread-" + (i + 1));rn t.start();rn synchronized (running) rn running++;rn rnrn rnrn rnrn public boolean isRunning() rn boolean r = true;rn synchronized (running) rn r = ( running != 0);rn rn return r;rn rnrn public void run() rnrn try rnrn //DO Somethingthingrnrn catch (Exception ex) rn ex.printStackTrace();rn rnrn System.out.println("Over");rn synchronized (running) rn running--;rn System.out.println("R" + running);rnrn rn rnrnrnrnrn
关于多线程同步的问题
我写了一个统计在线人数的bean,可是在删除超时用户的时候总抛出java.util.ConcurrentModificationException违例,可是重新刷新一下页面就又正常了,要删的用户也删除了,就是如果再有用户被删的时候他有会抛出违例,我看了文档,了解到这个违例是线程同步时出的问题,但是我还是不知道应该怎么解决,我对多线程的东西比较晕,哪位办帮忙看看,下面时源代码。rnrnOnLine.javarnrnpackage test.forum;rnrnimport java.util.*;rnimport javax.servlet.http.*;rnimport java.io.*;rnimport test.user.*;rnrnpublic class OnLinern rn private HashMap monitor;//key-session,value-userrn private int userCount=0; //在线用户数rn private int guestCount=0;//在线客人数rn private String errs;rn private HashMap users;rn private HashMap guests;rnrn //user是个类rn public OnLine(HttpSession session,User user) rn addUser(session,user);rn rn rn rn public synchronized void addUser(HttpSession session,User user)rn if(monitor==null)monitor=new HashMap(); rn monitor.put(session,user);rn intCount();rnrn private synchronized void removeUser(HttpSession session) rn monitor.remove(session); rn rn private User getUser(HttpSession session)rn User tmpUser=(User)monitor.get(session);rn return tmpUser;rn rn rn public int getUserCount () rn return (this.userCount); rn rnrn public int getGuestCount () rn return (this.guestCount); rn rn public HashMap getUsers()rn return this.users;rn rn public HashMap getGuests()rn return this.guests;rn rnrn private void intCount()rn rn Iterator keyIter=monitor.keySet().iterator();rn long now = System.currentTimeMillis(); rn int newUserCount=0;rn int newGuestCount=0;rn HashMap newUsers=new HashMap();rn HashMap newGusets=new HashMap(); rn while(keyIter.hasNext())rn HttpSession https = (HttpSession)keyIter.next();rn User tmpUser=getUser(https);rn if((now-tmpUser.getLastPostTime().getTime())>=180000)rn removeUser(https); rn else rn //统计在线人数rn if(tmpUser.getUsername()==null)rn newGusets.put(https,tmpUser);rn newGuestCount++; elsern newUsers.put(https,tmpUser);rn newUserCount++; rn rn rn rn users=newUsers;rn guests=newGusets;rn userCount=newUserCount;rn guestCount=newGuestCount;rn rnrnrnJSP 源码如下rn<%@ page import="com.wegood.greenzone.forum.*,rn com.wegood.greenzone.util.*,rn com.wegood.greenzone.user.*,rn java.util.*"rn contentType="text/html;charset=gb2312"%>rn<% OnLine onLine;rn HashMap onLineUsers;rn HashMap onLineGuests;rn Object intLock=new Object();rn int userCount;rn int guestCount; rn onLine=(OnLine)application.getAttribute("monitor");rn if (onLine==null)rn //out.print("onLine==null");rn synchronized(intLock)rn onLine=new OnLine(session,user);rn rn elsern //out.print("onLine!=null");rn synchronized(intLock)rn onLine.addUser(session,user);rn rn rn application.setAttribute("monitor",onLine);rn rn onLineUsers=onLine.getUsers();rn onLineGuests=onLine.getGuests();rn userCount=onLine.getUserCount();rn guestCount=onLine.getGuestCount(); rn rn %>rnrnrn
关于DELPHI5多线程同步的问题
各位朋友大家好,本人刚开始研究多线程,还有很多不明白的地方,望大家指教,谢谢!rn问题是这样的:rn定义两个线程,当按钮连接时执行连接创建一个线程序,连接成功后执行查询按扭再创建一个线程,现在问题是查询线程rn中无法利用 连接线程的SocketConnection1,如何同步呢?rn部分代码如下:rnrn定义:rn typern Tthread1 = class(Tthread)rn protectedrn procedure Execute;override;rn procedure getSocketConn;rn end;rnrn typern Tthread2 = class(Tthread)rn protectedrn procedure Execute;override;rn procedure getClientDataSet;rn end;rnrnprocedure Tthread1.Execute;rnbeginrnrn Tryrn FreeOnTerminate:=true;rn ConToolsFrm.SocketConnection1.ServerGUID:='2C8E3F43-ABE4-11D4-B352-00E04C67568C';rn ConToolsFrm.SocketConnection1.ServerName:='apply_tier.Apply_data';rn ConToolsFrm.SocketConnection1.Connected:=False;rn ConToolsFrm.SocketConnection1.Host:= ConToolsFrm.edtHost.Text;rn ConToolsFrm.SocketConnection1.Connected:=True;rn ShowMessage('连接成功!');rn Exceptrn ShowMessage('连接失败,请断开后再试!');rn ConToolsFrm.SocketConnection1.Connected:=False;rn end;rnend;rnrnprocedure Tthread2.Execute;rnvarrn sqlStr:string;rnbeginrn ConToolsFrm.ClientDataSet1.Close;rn ConToolsFrm.ClientDataSet1.RemoteServer:=ConToolsFrm.SocketConnection1;rn ConToolsFrm.ClientDataSet1.ProviderName:='provider7';rn sqlStr:=ConToolsFrm.edtSql.Text;rnrn ConToolsFrm.SocketConnection1.appserver.zyyf_pub_pro(sqlStr, 'o');rn [b]ConToolsFrm.ClientDataSet1.Open;[/b][color=#FF0000][/color] //该部分直接跳走没有运行rn if ConToolsFrm.ClientDataSet1.RecordCount=0 thenrn beginrn if ConToolsFrm.FindProcess('apply_tier.exe') then //中间层正在运行rn beginrn //重启 SOCKET SERVERrn ConToolsFrm.StartService('SocketServer');rn //关闭apply_tier进程rn ConToolsFrm.EndProcess('apply_tier.exe');rn end;rn end;rnend;rnrn//连接rnprocedure TConToolsFrm.btnConnectClick(Sender: TObject);rnbeginrn mythread1:=Tthread1.Create(false);rnend;rnrnprocedure TConToolsFrm.btnSelectClick(Sender: TObject);rnbeginrn mythread2:=Tthread2.Create(false);rnend;
一个关于多线程同步的问题
首先定义了一个全局变量rnint iCounter;rn并定义了如下一个临界区量rnCRITICAL_SECTION criCounter;rn线程主函数rnUINT MyThread(LPVOID lparam)rnrn for(int i=0;i<10;i++)rn rn EnterCriticalSection(&criCounter);rn int iCopy=iCounter;rn iCopy++;rn iCounter=iCopy;rn LeaveCriticalSection(&criCounter);rn rn return 0;rnrn在一个菜单响应函数添加了如下代码rnvoid CThreadApp::OnBeginThread() rnrn // TODO: Add your command handler code herern InitializeCriticalSection(&criCounter);rn HANDLE hThread[3];rn CWinThread* m_pThread1=AfxBeginThread(MyThread,NULL);rn CWinThread* m_pThread2=AfxBeginThread(MyThread,NULL);rn CWinThread* m_pThread3=AfxBeginThread(MyThread,NULL);rn hThread[0]=m_pThread1->m_hThread;rn hThread[1]=m_pThread2->m_hThread;rn hThread[2]=m_pThread3->m_hThread;rn WaitForMultipleObjects(3,hThread,TRUE,INFINITE);rn DeleteCriticalSection(&criCounter);rn if(iCounter==30)rn AfxMessageBox("实验成功");rn elsern AfxMessageBox("实验失败");rnrnrn最后的实验结果是编译时没问题可执行菜单命令时却失败了(弹出一个“实验失败”的对话框)rn这段代码参考了闻怡洋的一篇文章“进程/线程控制”的示范代码。rn但是将线程主函数改为如下形式就能执行成功rnUINT MyThread(LPVOID lparam)rnrn for(int i=0;i<10;i++)rn rn EnterCriticalSection(&criCounter);rn int iCopy=iCounter;rn Sleep(100); //这里是修改之处rn iCopy++;rn iCounter=iCopy;rn LeaveCriticalSection(&criCounter);rn rn return 0;rnrn请问高手们,代码的问题出在哪(本人是刚开始学写多线程程序,调试环境是win2000),难道说Sleep(100)有什么特别的作用?临界区对象不是可以保证同一时刻只有一个线程访问它吗?那还用得着让Sleep来把线程挂起一段时间?rnrnrnrnrnrnrnrnrnrnrn
关于多线程同步问题.
lock(Queue)rnrn //code here;rnrn我用lock锁住一个队列,让1000个线程,访问这个队列的时候,能1个1个取,使其不至于2个线程取到同一个对象.rn可是问题就来了,仅仅这么锁住还不行,会造成死锁.于是部分线程就返回不回来,然后就会丢失一部分数据.rn求大神指教,怎么让这段代码,既让多线程访问,既可以同步,又不早成死锁呢?小弟,在这里先谢过了.
多线程同步,关于Semaphore问题
我想让主线程发一个信号唤醒制定的一个线程,然后再由唤醒后的这个线程在发送另外一个信号唤醒另一个线程。rnrn主线程:rnArnrn...rnrnh1 = CreateSemaphore( NULL, cMax,cMax, NULL); // unnamed semaphorernrn printf("signal");rn if (hSemaphore == NULL) rnrn rn rn printf("CreateSemaphore 1 error: %d\n", GetLastError());rnrn rnrn if (!ReleaseSemaphore(h1,1, NULL) ) rn rn printf("Release h1 error: %d\n", GetLastError());rn rn Sleep(3000); rn CloseHandle(h1);rn..rnrnrn需要唤醒的第一个线程rnBrnrn...rnrnDWORD dwWaitResult;rndwWaitResult = WaitForSingleObject(h1,0L);rnrnswitch (dwWaitResult) rn rn case WAIT_OBJECT_0: rn rn ...rn h2 = CreateSemaphore(NULL,cMax,cMax,NULL); rn if (h2 == NULL) rnrn rn rn printf("CreateSemaphore 2 error: %d\n", GetLastError());rnrn rn if (!ReleaseSemaphore(h2,1, NULL) ) rn rn printf("Release h2 error: %d\n", GetLastError());rn rn Sleep(3000);rn CloseHandle(h2);rn rn rn rn...rnrnrnB要唤醒的线程rnCrnrn DWORD dwWaitResult;rndwWaitResult = WaitForSingleObject(hRecvSemaphore,0L);rn rn switch (dwWaitResult) rn rn rn case WAIT_OBJECT_0: rn rn ...rnrn rnrn break; rnrn...rnrnrn可是为什么Release h2 error?
关于多线程同步的问题??
经常看到这样的代码,多个线程读取一个共享变量时,也要进行同步处理。rn既然可以保证不会同时有更改操作,为什么还要进行同步那?
关于多线程同步问题
class threadMeng rn public static void main(String[] args)rn threadmm mt=new threadmm();rn rn // mt.start();rn new Thread(mt).start();//这样可以多个一样的线程rn new Thread(mt).start();rn new Thread(mt).start();rn new Thread(mt).start();rn //while(true)rn rn System.out.println("main:"+Thread.currentThread().getName());rn rnrn class threadmm implements Runnablern Object obj=new Object();rn int i=1;// 如果 i 在run 方法里定义的话就不能同步rn int j=10;rn boolean b=true;rn public void run() rn while(b)rn synchronized(obj)rn if(i=j)rn b=false;rn rn rn rnrnrnint i=1;// 如果 i 在run 方法里定义的话就不能同步 rn这是为何呢? rn
关于多线程同步的问题------------〉〉〉〉〉〉〉〉〉〉〉
多线程调用同一个函数(一个全局函数,不是对象的函数),函数内部的局部变量会不会受到影响?rnrn比如:rnrnprocedure test(filename:string);rnvarrni:integer;rnsl:tstringlist;rnbeginrn i:=0;rn sl:=tstringlist.create;rn randomize;rn for i:=1 to 10000 dorn beginrn sl.add(inttostr(i));rn sleep(random(100));rn end;rn sl.savetofile(filename);rn sl.free;rnend;rnrn当2个线程调用这个函数的时候,如果传入不同文件名,到执行完后,分别看两个文件,各自显示的是不是从1到10000连续递增的数??rn
关于多线程同步。
在vb中怎么实现多线程同步。rn我想到两种方法rn1、使用文件保存一个变量。读取和修改变量时,必须锁定文件。这样就可以保证只有一个线程访问这个变量。rn2、我想使用CreateMutex建立互斥对象。rnrn但是有的时候能够建立,有的时候建立不了,返回句柄是0。rn MyMutexName = "Mutex1"rn hMyMutex = CreateMutex(0, 0, MyMutexName)rn而且我退出也关闭了句柄。rnrn不知道大家使用什么方法,请大家指点。
关于多线程同步
[code=C/C++]rn#include rn#include rn#include rn#include rnusing namespace std;rnrnint index = 10;rnHANDLE hMutex;rnDWORD WINAPI Fun1(LPVOID p)rnrn while (1)rn rn WaitForSingleObject(hMutex, INFINITE);rn if (index > 0)rn rn cout << "index:" << index << " "<< "线程1号" << endl;rn index--;rn rn ReleaseMutex(hMutex);rn rn return 0;rnrnDWORD WINAPI Fun2(LPVOID p)rnrn while (1)rn rn WaitForSingleObject(hMutex, INFINITE);rn if (index > 0)rn rn //Sleep(1);//这句不加,开始的时候不会同步rn cout << "index:" << index << " "<< "线程2号" << endl;rn index--;rn rn ReleaseMutex(hMutex);rn rn return 0;rnrnint main()rnrn HANDLE Thread1;rn HANDLE Thread2;rn Thread1 = CreateThread(NULL, 0, Fun1, 0, 0, 0);rn Thread2 = CreateThread(NULL, 0, Fun2, 0, 0, 0);rn CloseHandle(Thread1);rn CloseHandle(Thread2);rn hMutex = CreateMutex(NULL, false, NULL);rn Sleep(100);rn return 0;rnrnrn[/code]rn结果:rn[code=C/C++]rnindex:index:1010 线程1号线程2号rnrnindex:8 线程1号rnindex:7 线程2号rnindex:6 线程1号rnindex:5 线程2号rnindex:4 线程1号rnindex:3 线程2号rnindex:2 线程1号rnindex:1 线程2号rn请按任意键继续. . .[/code]
关于BackgroundWorker占用线程问题
大家好,rn我以前编写了一个用BackgroundWorker处理一个导入过程的实例。rn当点击“导入”按钮选择完要导入的文件后,程序将运行bkWorker.RunWorkerAsync()将导入过程交给后台线程。rn那么此时我再次点击“导入”按钮,仍可以打开一个OpenFileDialog的实例。rnrn但是我刚刚编写了一个简单的窗体,发现在将更新进度条value的程序交给线程后,主线程无法像之前一样继续点击“导入”按钮。rnrn麻烦大家指导一下,多谢。rnrnpublic partial class Form1 : Formrn rn private BackgroundWorker bkWorker = new BackgroundWorker();rnrn public Form1()rn rn InitializeComponent();rnrn bkWorker.WorkerReportsProgress = true;rn bkWorker.WorkerSupportsCancellation = true;rn bkWorker.DoWork += new DoWorkEventHandler(DoWork);rn bkWorker.ProgressChanged += new ProgressChangedEventHandler(ProgessChanged);rn bkWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(CompleteWork); rn rnrn private void 开始_Click(object sender, EventArgs e)rn rn OpenFileDialog dlg = new OpenFileDialog();rn dlg.Title = "请选择要导入的文件:";rn dlg.Filter = "Excel文件(*.xls)|*.xls|所有文件|*.*";rn dlg.Multiselect = true;rnrn if (dlg.ShowDialog() == DialogResult.OK)rn rn progressBar1.Maximum = 1000000;rn bkWorker.RunWorkerAsync();rn rn rnrn private void DoWork(object sender, DoWorkEventArgs e)rn rn for (int i = 0; i < 1000000; i++)rn rnrn bkWorker.ReportProgress(i);rn rn rnrn public void ProgessChanged(object sender, ProgressChangedEventArgs e)rn rn progressBar1.Value = e.ProgressPercentage;rn rnrn public void CompleteWork(object sender, RunWorkerCompletedEventArgs e)rn rn MessageBox.Show("Done!");rn rn
请教关于TIMER和BackgroundWorker的问题
各位好,本人在编程的时候遇到这样的问题,在前台提供用户界面的正常操作,而后台需要通过WEB SERVICE接口每隔5分钟从远程服务器取得大量数据.我目前使用的是TIMER,这时候会出现界面无反应的问题.rnrnrn请问如何既可以每隔一定时间正常地执行后台任务,又不影响界面的操作呢?据了解BackgroundWorker是不错的选择,但是我不知道如何使用BackgroundWorker实现TIMER的定时功效.rnrn谢谢.rn
关于backgroundworker和serialPort合用的问题
我想实现在backgroundworker进行一个串口误码率测试的程序。下面是主要代码,C++CLI的。我看这边人气旺点,呵呵rn结构很简单,一个扭启动backgroundworker,一个结束,另外三个时间分别作后台,和更新进度。rn将这个功能编写到单独的程序中是没问题的。但是这是我的一个大程序的一部分。其中有类似的结构。用的是同一个backgroundworker控件。rn经常会出现System.IndexOutOfRangeException异常,这个应该不是我的程序的问题,因为这些代码在另一处是正常的,并且在大程序上出现异常也有随机性。rn另一个问题就是有时后台程序没法停止,而且把串口占用着,就只能重启下位机系统了rn本人新手分少,见谅rn[code=C/C++]rn private: array^ RdmByteArray(int num)//num MUST larger than 0rn array^ bytearray = gcnew array(num);rn Random^ random = gcnew Random;rn for(int i=0;i( random->Next() );rn rn return bytearray;rn rn private: System::Void button3_Click(System::Object^ sender, System::EventArgs^ e) rn sPort->Close();rn tryrn sPort->Open(); rnrn catch(System::IO::IOException^ e)rn MessageBox::Show("没有找到串口", L"About A TestSystem Application", MessageBoxButtons::OK, MessageBoxIcon::Exclamation);rn return;rn catch(UnauthorizedAccessException^ e)rn MessageBox::Show("对串口的访问被拒绝,可能被其他程序占用" , L"About A TestSystem Application",rn MessageBoxButtons::OK, MessageBoxIcon::Exclamation);rn return;rn rn button3->BackColor = Color::Green;rn rn private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) rnrn rn private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) rn BGW->RunWorkerAsync(sPort);rn rn private: System::Void BGW_DoWork(System::Object^ sender, System::ComponentModel::DoWorkEventArgs^ e) rnrn array^ cmd = 0xcd,0xcd,0xcd, 0xcd,0x33,0x33,0x10,0x01,0x00,0x00,0x00,0x00,0x5a,0x5a,0x5a,0x5a,0xda,0xda,0xda,0xda;//命令字部分和数据字头rn array^ dataend = 0xa5,0xa5,0xa5,0xa5;//数据字尾rn Int16 dataNum = 16;//32Bit word最大为16个字rn cmd[11] = (safe_cast(dataNum))*4;//Uinit:Bytesrn array^ RdmData = gcnew array(dataNum*4);//随机的测试数据rn array^ tmpcmd = gcnew array(cmd->Length + dataNum*4 + dataend->Length);//用于拼装命令rn array^ cmdRec = gcnew array(100);//接收到的数据rnrn cmd->Copy(cmd, 0, tmpcmd, 0, cmd->Length );//头部装入rn dataend->Copy(dataend, 0, tmpcmd, cmd->Length + RdmData->Length , dataend->Length );//尾部装入rnrn int totalB = 0, errB = 0;//用于记录的总数和误码数rnarray^ databack = gcnew array(dataNum*4);rn RdmData = RdmByteArray(dataNum * 4);rn RdmData->Copy(RdmData, 0, tmpcmd, cmd->Length, RdmData->Length );rn int numRecord = 0;//记录当前周期收到的数据个数rn int BtoR = 0;//记录缓存中需要读的数rnrn int i ,j;rnrn while( !BGW->CancellationPending )rnrnrnrn#pragma region 串口发送和接收rn sPort->DiscardInBuffer();//清空接收缓存,避免相互干扰rnrn sPort->Write(tmpcmd, 0, tmpcmd->Length);//发送命令rnrn Array::Clear(cmdRec, 0, 100);//初始化数据rn numRecord = 0;//记录当前周期收到的数据个数rn BtoR = 0;//记录缓存中需要读的数rnrnrn for(i=0;i<0xffffff;i++);//延时,必须得,否则会发生错误,推出测试rnrn for(j=0; j<0xffffff; j++)//接收数据,符合预定条件即退出rn BtoR = sPort->BytesToRead;rn if(BtoR != 0 && (numRecord+BtoR)<100 )rn sPort->Read(cmdRec, numRecord, BtoR);rn numRecord += BtoR;rn BGW->ReportProgress(777);rn if( numRecord>100 )//收到太多数据rn BGW->ReportProgress(555);rn break;rn else if ((cmdRec[19] == 0x5a) && (cmdRec[15] ==0 ))//没有数据字时rn BGW->ReportProgress(666);rn break;rn else if( (cmdRec[numRecord-4] == 0xa5) && (cmdRec[numRecord-1] == 0xa5) )//有数据字时rn BGW->ReportProgress(999);rn break;rn rn rn if(j== 0xffffff)rn BGW->ReportProgress(0);//代表超时rnrnrn rnrn#pragma endregionrn BGW->ReportProgress(222);rnrn if(cmdRec[10]==0x00 && cmdRec[11]==0x00)rn totalB += dataNum*4;rn BGW->ReportProgress(totalB);rnrn int RecDataNum = (cmdRec[14]<<8) + (cmdRec[15]) - 4 ;//状态字rnrn //如果返回数据已发送数据个数不等,直接进行下一次测试,本次全部作为误码rn if(RecDataNum != (dataNum*4))rn errB += 10;rn BGW->ReportProgress(-errB);rn continue;rn rnrn //提取出返回的数据,与原数据比较并显示在文本框中rn rn for(int i=28;i< 28 + (RecDataNum);i+=2)rn databack[i-28] = cmdRec[i+1];//交换两个字节,由测试系统返回的是相反的rn databack[i+1-28] = cmdRec[i];rn if(RdmData[i-28] != databack[i-28]) errB++;rn if(RdmData[i-28 +1] != databack[i-28 +1]) errB++;rn rnrn rnrn BGW->ReportProgress(-errB-1);rnrn elsern BGW->ReportProgress(0);//报告0,代表通信错误rn //continue;rn rnrn rn //Thread::Sleep(1200);rn BGW->ReportProgress(333);rn e->Cancel = true;rn return;rn rn private: System::Void BGW_ProgressChanged(System::Object^ sender, System::ComponentModel::ProgressChangedEventArgs^ e) rn if(e->ProgressPercentage>0)rn progressBar1->Value = e->ProgressPercentage % 100;rn label1->Text = e->ProgressPercentage.ToString();rn elsern if( e->ProgressPercentage != (-1))rn textBox1->Text += ("ERRROR RATE : " + (-1-e->ProgressPercentage).ToString() + ";此时总通信息量:" + label1->Text + "\r\n" );rn rnrn rn private: System::Void BGW_RunWorkerCompleted(System::Object^ sender, System::ComponentModel::RunWorkerCompletedEventArgs^ e) rn textBox1->Text += "BGWorker结束了";rn rn private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e) rn BGW->CancelAsync();rn rn ;rnrnrn[/code]
关于BackgroundWorker控件进度条的问题?
没有循环的一个运行时间较长而且不定时的一个程序段,怎样利用BackgroundWorker控件来在其开始运行的同时开始显示进度条?因为没有循环不知道怎样获得运行的进度步长和最大值。
backgroundWorker 问题
using System;rnusing System.Collections.Generic;rnusing System.ComponentModel;rnusing System.Data;rnusing System.Drawing;rnusing System.Text;rnusing System.Windows.Forms;rnrnnamespace Xianchengrnrn public partial class Form1 : Formrn rn public Form1()rn rn InitializeComponent();rn rnrn private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)rn rn tryrn rnrn Test(e);rn rn catch (Exception ex)rn rn MessageBox.Show(ex.Message);rn rn rn rnrn private void Test(DoWorkEventArgs e)rn rn tryrn rn throw new Exception ("测试");rn rn catch (System.Net.WebException ex)rn rn MessageBox.Show(ex.Message);rn rn rn rn rnrn private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)rn rn rn rnrn private void button1_Click(object sender, EventArgs e)rn rn backgroundWorker1.RunWorkerAsync();rn rn rn rnrnrnrn当我执行时会出错,提示说 未处理的targetInvocationException rn请问为什么,怎么处理,我不太会backgroundWorkerrn谢谢
BackgroundWorker的问题!
有谁用过2005的BackgroundWorker这个控件!rn应为有时候数据量过大等原应,程序很容易僵硬!rn这个控件是2005出的后台处理的东东,可不是太会用,rn我想做的是群发邮件,用这个来处理发邮件的过程,成功则往一个LISTVIEW里加成功的邮件地址,rn失败则往别的LISTVIEW里加.rn有高手能指点下吗?
关于BackgroundWorker资源占用问题
累加一int值,通过BackgroundWorker向窗口的label控件和progressBar显示,在拖动窗口时感觉比较占用资源,反应rn较慢,但用thread建立线程则几乎没有影响?
backgroundworker问题
我想实现在界面上实时更新一个label的值,用for循环100000此,用的backgroundworker方法和线程+委托的两种方法:[code=C#]rn//BackgroundWorkerrn DateTime now;rn TimeSpan ts;rn private void button3_Click(object sender, EventArgs e)rn rn if (backgroundWorker1.IsBusy)rn return;rn now = DateTime.Now;rn backgroundWorker1.RunWorkerAsync();rn rnrn private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)rn rn BackgroundWorker bw = sender as BackgroundWorker;rn for (int i = 0; i < 100000; i++)rn rn bw.ReportProgress(i,100000);rn [color=#FF0000]Thread.Sleep(1);[/color] rn rnrn private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)rn rn label3.Text = e.ProgressPercentage.ToString();rn progressBar3.Value = e.ProgressPercentage / 1000;rn rnrn private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)rn rn progressBar3.Value = 100;rn ts = DateTime.Now - now;rn MessageBox.Show("BackgroundWorker:"+ts.TotalMilliseconds);rn rn //線程+委託rn private void button2_Click(object sender, EventArgs e)rn rn Thread th = new Thread(new ThreadStart(ShowNum));rn th.Start();rn rn public delegate void UpdateText(int i);rnrn public void UpdateTextLabel(int i)rn rn if (label2.InvokeRequired)rn rn UpdateText ut = new UpdateText(UpdateTextLabel);rn label2.Invoke(ut, i);rn rn elsern rn label2.Text = i.ToString();rn progressBar2.Value = i / 1000;rn rn rnrn public void ShowNum()rn rn DateTime now = DateTime.Now;rn for(int i =0;i< 100000;i++)rn rn UpdateTextLabel(i);rn rn DateTime now1 = DateTime.Now;rn TimeSpan ts = now1 - now;rn MessageBox.Show("線程+委託:" + ts.TotalMilliseconds);rn rn[/code]rnrn我想问得时为什么在backgroundworker中用加入sleep,最初我没加,结果label没有实时更新,加了以后达到效果,但是速度变慢了,而线程+委托方法,速度快,但是cpu占用率却很高,谁能帮我解答一下这些问题
backgroundworker的问题
我通过backgroundworker新起一个线程进行文件上传,我想实现在文件(文件可能有点大)上传过程中终止上传,发现CancelAsync无法终止该进程,如果是循环上传多个文件可以终止循环过程,但如果是仅上传单个的话就出现终止无效的问题,请问有什么解决方法
BackgroundWorker问题
我在一个类中响应菜单事件,并把该事件放入BackgroundWorker中运行,在该类中事先已创建一个TabControl和System.Windows.Forms.TabPage控件,而在事件响应处理函数中要用到this.tbDataTableDisp.TabPages.Add(pPage);添加一个页面,运行代码后出现“线程间操作无效,从不是创建控件‘。。。’的线程访问它”,请问遇到这种问题应该怎么处理?
BackgroundWorker的问题
小弟在程序中使用到了BackgroundWorker处理数据rn现在问题是数据变成了一个数组rn需要处理这批数据的时候isbusy属性也无法很好的控制rn刚刚用sleep程序直接假死.rnrn简单的说我想处理两批数据,怎么控制在第一批数据完全处理完后再处理第二批数据,项目中用到了BackgroundWorker处理第一批数据
backgroundworker
在android和ios中实现类似c#的BackgroundWorker的代码
BackgroundWorker
BackgroundWorker 开发教程实例 无中生有
Backgroundworker
.net 2.0 里面的东西rnrn比如一个对象:MyBackgroundWorkerrnrn执行:MyBackgroundWorker.CancelAsync()rnrn然后后台线程里判断:MyBackgroundWorker.CancellationPending,一但为true则退出...rnrnrn问题:有其他办法关闭当前这个后台现成吗?
关于backgroundworker的使用方法
使用backgroundwork创建的一个有关进度条的小程序,包含代码,
关于BackgroundWorker的CancelAsync()
大家好,rn我最近正在研究BackgroundWorker的CancelAsync()事件。rn我做的窗体中有两个按钮。当点击“导入”按钮时,实现将EXCEL文件导入到SQL数据库中。rn现在想添加一个“取消”按钮,即终止该线程。rnrn查了很多代码,发现跟我的代码思路不太一样。大家基本都是写在循环里面了,而我的代码里好像不太适合添加这种循环来实时判断CancellationPending,所以想请大家帮忙看看。rnrn如果您能再多指点几句,那就更是感激不尽了。rnrn多谢大家。rnrnpublic partial class Form1 : Formrn rn int Total = 0;rnrn string[] FileNames;rnrn private BackgroundWorker bkWorker = new BackgroundWorker();rnrn public Form1()rn rn InitializeComponent();rnrn bkWorker.WorkerReportsProgress = true;rn bkWorker.WorkerSupportsCancellation = true;rn bkWorker.DoWork += new DoWorkEventHandler(DoWork);rn bkWorker.ProgressChanged += new ProgressChangedEventHandler(ProgessChanged);rn bkWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(CompleteWork); rnrn rnrnrnrn private void 导入_Click(object sender, EventArgs e)rn rn rnrn OpenFileDialog dlg = new OpenFileDialog();rn dlg.Title = "请选择要导入的文件:";rn dlg.Filter = "Excel文件(*.xls)|*.xls|所有文件|*.*";rn dlg.Multiselect = true;rnrn rnrnrn if (dlg.ShowDialog() == DialogResult.OK)rn rnrn FileNames = dlg.FileNames;rnrn foreach (string FileName in FileNames)rn rn OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;Data Source=" + FileName);rnrn conn.Open();rnrn DataTable table = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);rnrn for (int i = 0; i < table.Rows.Count; i++)rn rn string TableName = table.Rows[i]["TABLE_NAME"].ToString();rnrn if ((TableName.Substring(TableName.Length - 1, 1) == "$") || (TableName.Substring(0, 1) == "'"))rn rn if ((TableName.Substring(TableName.Length - 2, 1) == "$"))rn rn char[] TrimChar = '\'' ;rn TableName = TableName.Trim(TrimChar);rn TableName = TableName.Substring(0, TableName.Length - 1);rn rn elsern rn char[] TrimChar = '\'', '$' ;rn TableName = TableName.Trim(TrimChar);rn rnrn DataSet DS = new DataSet();rnrn string strExcel = string.Format("select * from [0$]", TableName);rnrn OleDbDataAdapter Adapter = new OleDbDataAdapter(strExcel, conn);rnrn OleDbCommandBuilder Builder = new OleDbCommandBuilder(Adapter);rnrn Adapter.Fill(DS, TableName);rnrn Total = Total + DS.Tables[0].Rows.Count;rnrnrn Builder.Dispose();rn Adapter.Dispose();rn DS.Dispose();rn rn rn rn table.Dispose();rn conn.Dispose();rn rnrn this.progressBar1.Maximum = Total;rnrn bkWorker.RunWorkerAsync();rnrn rnrnrn rnrn public void DoWork(object sender, DoWorkEventArgs e)rn rn rn string connString = "Server=GFKSAS3;UID=sa;PWD=f0reC0urt;Database=Northwind";rnrn foreach (string FileName in FileNames)rn rn OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;Data Source=" + FileName);rnrn conn.Open();rnrn DataTable table = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);rnrn for (int i = 0; i < table.Rows.Count; i++)rn rn string TableName = table.Rows[i]["TABLE_NAME"].ToString();rnrn if ((TableName.Substring(TableName.Length - 1, 1) == "$") || (TableName.Substring(0, 1) == "'"))rn rn if ((TableName.Substring(TableName.Length - 2, 1) == "$"))rn rn char[] TrimChar = '\'' ;rn TableName = TableName.Trim(TrimChar);rn TableName = TableName.Substring(0, TableName.Length - 1);rn rn elsern rn char[] TrimChar = '\'', '$' ;rn TableName = TableName.Trim(TrimChar);rn rnrnrn TransferData(FileName, TableName, connString);rnrnrn rn rn table.Dispose();rn conn.Dispose();rn rnrn rnrn public void ProgessChanged(object sender, ProgressChangedEventArgs e)rn rn rn this.progressBar1.Value = e.ProgressPercentage;rnrn this.label1.Text = Convert.ToString(((e.ProgressPercentage) * 100 / progressBar1.Maximum)) + "%";rnrn rnrn public void CompleteWork(object sender, RunWorkerCompletedEventArgs e)rn rn this.progressBar1.Value = Total;rn this.label1.Text = "完成!";rn rnrnrn public void TransferData(string excelFile, string sheetName, string connectionString) rn rnrn tryrn rn DataSet DS = new DataSet();rnrn string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + excelFile + ";Extended Properties=Excel 8.0";rnrn OleDbConnection conn = new OleDbConnection(strConn);rnrn conn.Open();rnrn string strExcel = string.Format("select * from [0$]", sheetName);rnrn OleDbDataAdapter Adapter = new OleDbDataAdapter(strExcel, conn);rnrn OleDbCommandBuilder Builder = new OleDbCommandBuilder(Adapter);rnrn Adapter.Fill(DS, sheetName);rnrn using (System.Data.SqlClient.SqlBulkCopy bcp = new System.Data.SqlClient.SqlBulkCopy(connectionString))rn rnrn int Done = 0;rn bcp.BatchSize = 1000;rn bcp.NotifyAfter = 1000;rn bcp.DestinationTableName = "test";rn bcp.WriteToServer(DS.Tables[0]);rnrn Done = Done + 1000;rn bkWorker.ReportProgress(Done);rn rn rnrn rn conn.Dispose();rn Adapter.Dispose();rn Builder.Dispose();rn DS.Dispose();rn rnrn catch (Exception ex)rn rn System.Windows.Forms.MessageBox.Show(ex.Message);rn rn rnrn private void 取消_Click(object sender, EventArgs e)rn rn bkWorker.CancelAsync();rn rnrnrnrn
关于BackgroundWorker多次调用
若先后调用两次RunWorkerAsync();rn那么这两次调用的执行是顺序的吗。rn后台工作只有一个线程工作,按调用的先后顺序执行rn还是会有两个线程分别执行,不一定哪个先执行完?
关于backgroundworker的取消
void bw_DoWork(object sender, DoWorkEventArgs e)rn rn this.Downloader.RunThread(worker); rnrn rn当用户取消时,如何中止这个下载线程啊?
多线程同步的问题?
我想实现一种功能:分配一块内存区域,在一个线程访问或使用的时候,别的所有将使用该内存区域的线程就排队等待。我看了Windows的多线程同步的书,可那些对象可以实现代码级的多线程同步,就是说给定的代码是固定的,然后别的线程在使用内存区域的时候可实现排队同步。在WINDOWS编程中有没有数据级的多线程同步方法,就是说在一个线程使用一个内存区的时候别的线程就使用不了该区域,同时各线程对内存数据区的处理方法可以自定,可以变化,不受“类”方法的限制。rnrn打个比方:mov 00000001H,01H(在0~4k页中)rn mov 00000002H,02Hrn mov 00000003H,03Hrn mov 00000004H,04Hrn 以上为一个线程的代码,这时另一个线程就会等待这一段代码的执行完毕后(不会被系统切换而使以上代码的完整性被破坏),再执行另一段代码:rnadd 00000001H,02Hrnadd 00000002H,05Hrnadd 00000003H,03Hrnadd 00000004H,01Hrn
相关热词 c++和c#哪个就业率高 c# 批量动态创建控件 c# 模块和程序集的区别 c# gmap 截图 c# 验证码图片生成类 c# 再次尝试 连接失败 c#开发编写规范 c# 压缩图片好麻烦 c#计算数组中的平均值 c#获取路由参数