C#多線程共享數據
2024-07-21 02:30:03
供稿:網友
在多線程編程中,我們經常要使用數據共享.c#中是如何實現的呢?很簡單,只要把你要共享的數據設置成靜態的就可以了.關鍵字static .如下:
static queue q1=new queue();
static int b=0;
在這里我定義了一個整形變量b和隊列q1.
接下去就可以創建多線程代碼了.如下:
mythread myc;
thread[] myt;
myt=new thread[10];
myc=new mythread();
for(int i=0;i<10;++i)
{
myt[i]=new thread(new threadstart(myc.dofun));
// system.console.writeline("<<{0}>>",myt[i].gethashcode());
myt[i].start();
thread.sleep(1000);
}
你可能驚奇的發現這里使用了一個類實例myc.在起初的設計中我使用了mythread數組,對于本例來說這沒有什么關系,當線程要使用不同的操作時,那就要使用其他的類實例了.
以下是完整的代碼:
using system;
using system.threading;
using system.collections;
namespace sharethread
{
class mythread
{
static queue q1=new queue();
static int b=0;
public void dofun()
{
lock(this)
{
++b;
q1.enqueue(b);
}
system.console.writeline("b:{0}--------------",b);
printvalues( q1 );
}
public static void printvalues( ienumerable mycollection )
{
system.collections.ienumerator myenumerator = mycollection.getenumerator();
while ( myenumerator.movenext() )
console.write( "/t{0}", myenumerator.current );
console.writeline();
}
}
/// <summary>
/// class1 的摘要說明。
/// </summary>
class classmain
{
/// <summary>
/// 應用程序的主入口點。
/// </summary>
[stathread]
static void main(string[] args)
{
mythread myc;
thread[] myt;
myt=new thread[10];
myc=new mythread();
for(int i=0;i<10;++i)
{
myt[i]=new thread(new threadstart(myc.dofun));
// system.console.writeline("<<{0}>>",myt[i].gethashcode());
myt[i].start(); //線程運行
thread.sleep(1000);//主線程睡眠
}
system.console.read();//等待完成,dos窗口不會馬上關閉了.
}
}
}