Aller au contenu
Règlement du forum ×
IPTV et arnaques ×

passer des parametres a un thread C#


zaki

Messages recommandés

salut les amis,

je dois faire passer des paramètres a un thread (en c#) , mais je ne sais pas comment , j'ai essayer avec parametrizedThreadStart en suivant qlq exemples sur le net mais ca n'a pas marcher

 

voila un peut le code

 

public void receiver(Socket sc)
[color="Black"]{
...
 }

private void button1_Click(object sender, EventArgs e)
{
...
Socket client = main_sock.accept();
[color="Red"]Thread t = new Thread(new ParameterizedThreadStart(receiver));[/color]
t.Start(client); 
....
}[/color]

aider moi SVP

 

merci d'avance !

Lien vers le commentaire
Partager sur d’autres sites

salut les amis,

je dois faire passer des paramètres a un thread (en c#) , mais je ne sais pas comment , j'ai essayer avec parametrizedThreadStart en suivant qlq exemples sur le net mais ca n'a pas marcher

 

voila un peut le code

 

public void receiver(Socket sc)
[color=Black]{
...
 }

private void button1_Click(object sender, EventArgs e)
{
...
Socket client = main_sock.accept();
[color=Red]Thread t = new Thread(new ParameterizedThreadStart(receiver));[/color]
t.Start(client); 
....
}[/color]

aider moi SVP

 

merci d'avance !

 

Your code above won't work because ParameterizedThreadStart takes only delegates with object parameters.

 

Also you don't need the ParameterizedThreadStart any more, the Thread itself takes delegates.

 

Correct code

 

public void receiver([color=Red]object[/color] sc)
[color=Black]{
 [color=Red] Socket c = sc as Socket;
  if(c != null)[/color]
  {
     //do some work
  }
}[/color]
[color=Black]private void button1_Click(object sender, EventArgs e)
{
   ...
   Socket client = main_sock.accept();
   [color=Red]Thread t = new Thread(receiver);[/color]
   t.Start(client); 
....
}[/color]

 

Try it and let us know.

Modifié par Darkvader
Lien vers le commentaire
Partager sur d’autres sites

Salem,

 

Si t'es encore entrain de développer ton application de chat avec les sockets, je crois que je t'ai déjà répondu ICI concernant les AsyncCallBack et le multi-threading implicite, resté sans réponse.

 

mais je continue à dire que le meilleur moyen de faire ton IM est d'utiliser les AsyncCallBack

 

Ok je sorts.

 

 

merci bcp mourad khouya , mais j'hésite encore pour utiliser AsyncCallBack

 

Try it and let us know.

ca tres bien fonctionnée, Thx a lot !!

 

Voila mon projet d'IM opensource fait en VB.NET 1.1

 

http://code.google.com/p/devilmessenger/

 

@+

merci bcp pour le code frere !!

Modifié par zaki
Lien vers le commentaire
Partager sur d’autres sites

  • 4 weeks later...

bonjour,

concernant mon application toujours (messagerie instantanée) , je dois ajouter une fonctionnalité pour le partage de fichiers,c-a-d:

les clients connectés au serveur de messagerie ont la possibilité de mettre et télécharger des fichiers qui se trouve dans un dossier partagé dans le serveur .

mais franchement je ne sais pas quoi utiliser et d'où commencer, est ce que je dois utiliser le transfert via les sockets, installer un serveur ftp dans le poste serveur...etc , Aider moi svp;

 

merci d'avance !

Lien vers le commentaire
Partager sur d’autres sites

Salem,

 

Je crois que ces deux liens répondront à tes questions :

Commande FTP avec C#

 

Suite :)

 

Sinon si tu comptes faire un un transfert de fichier simple de client à client ou via le serveur je crois que le mieux serait de définir ton propre petit protocole :) t'as largement de quoi faire.

 

merci bcp khouya

Lien vers le commentaire
Partager sur d’autres sites

  • 3 weeks later...

Socket client = main_sock.accept();
   Thread t = new Thread(receiver);

devient

 

Socket client = main_sock.accept();
   Thread t = new Thread(delegate () { receiver ( client ) ; });

 

sinon pourquoi ne pas utiliser les nouveautés du framework, pour faire un chat avec WCF sa prend 5 minute, en plus tu peux changer de protocole en 10 seconde (en changeant juste un mot dans la configuration genre tcp devient http).

Lien vers le commentaire
Partager sur d’autres sites

 

Socket client = main_sock.accept();
   Thread t = new Thread(delegate () { receiver ( client ) ; });

 

Both solutions are right but your code won't work because that delegate needs to match ThreadStart which takes a parameter.

 

so your code needs to be as follows:

 

Socket client = main_sock.accept();
   Thread t = new Thread(delegate (object sock) { receiver ( client ) ; });

Modifié par Darkvader
Lien vers le commentaire
Partager sur d’autres sites

eux non!!

19.2.1. Passing Data to a Thread

Let's say we want to pass an argument to the method on which a thread starts.

To make this possible, Thread's constructor is overloaded to accept either of two delegates:

public delegate void ThreadStart( );

public delegate void ParameterizedThreadStart (object obj);

 

The limitation of ParameterizedThreadStart is that it accepts only one argument. And because it's of type object, it usually needs to be cast. An alternative is to use the parameterless ThreadStart in conjunction with an anonymous method as follows:

static void Main(  )
{
 Thread t = new Thread (delegate(  ) { Print ("Hello from t!"); });
 t.Start(  );
}
static void Print (string message) { Console.WriteLine (message); }

The advantage is that the target method (in this case, Print) can accept any number of arguments, and no casting is required.

 

Cf C# 3.0 in a Nutshell

Lien vers le commentaire
Partager sur d’autres sites

eux non!!

static void Main(  )
{
 Thread t = new Thread (delegate(  ) { Print ("Hello from t!"); });
 t.Start(  );
}
static void Print (string message) { Console.WriteLine (message); }

Cf C# 3.0 in a Nutshell

 

 

I agree, this one should work, only when you do t.Start(), but in case of Zaki's code which is t.Start(client), your code will throw an exception because it needs a matching parameter.

Modifié par Darkvader
Lien vers le commentaire
Partager sur d’autres sites

Rejoindre la conversation

Vous pouvez publier maintenant et vous inscrire plus tard. Si vous avez un compte, connectez-vous maintenant pour publier avec votre compte.

Invité
Répondre à ce sujet…

×   Collé en tant que texte enrichi.   Coller en tant que texte brut à la place

  Seulement 75 émoticônes maximum sont autorisées.

×   Votre lien a été automatiquement intégré.   Afficher plutôt comme un lien

×   Votre contenu précédent a été rétabli.   Vider l’éditeur

×   Vous ne pouvez pas directement coller des images. Envoyez-les depuis votre ordinateur ou insérez-les depuis une URL.

  • Messages

    • The environmental impact of straws extends far beyond their disposal—manufacturing processes themselves contribute significantly to carbon emissions. As an industry-leading Chinese Straw Manufacturer, Yiwu Double-Tong Daily Necessities Co., Ltd. has implemented groundbreaking measures to transform production into a model of circular economy principles. From solar-powered factories to zero-waste material recovery systems, sustainable manufacturing is proving that eco-friendly straws can be made with minimal environmental footprint. Energy innovation sits at the core of carbon reduction strategies. Yiwu Double-Tong's flagship facility in Zhejiang Province operates on 70% renewable energy, with rooftop solar panels generating 1.2 megawatts annually—enough to power the entire injection molding process for PLA straws. The remaining energy needs are met through purchased wind power credits, making this Chinese Straw Manufacturer one of the first in the industry to achieve Scope 2 carbon neutrality. Heat recovery systems capture waste thermal energy from machinery, repurposing it to pre-dry bamboo fibers, reducing energy consumption by 15%. Material efficiency breakthroughs are equally transformative. Traditional straw production generates up to 8% material waste from trimming and molding flash. Yiwu Double-Tong's closed-loop system recycles 100% of this waste—PLA scraps are reprocessed into 3D printing filament, while rice husk byproducts become biofuel pellets for heating. Even wastewater is treated through constructed wetlands where aquatic plants filter out non-toxic residues, achieving 90% water reuse rates. The supply chain has been radically optimized for sustainability. By sourcing bamboo from certified regenerative farms in Anji (where new shoots grow 91cm daily), the company ensures rapid carbon sequestration. Transportation emissions are slashed through a "production cluster" model—straw materials, molds, and finished goods are all manufactured within a 15km radius, eliminating 280 tons of CO₂ annually compared to dispersed operations. Third-party certifications validate these efforts: · ISO 14064-1:2018 verification for greenhouse gas inventories · Cradle to Cradle Gold certification for material health · Solar Impulse Foundation's Efficient Solution label Emerging technologies promise further reductions. Yiwu Double-Tong is piloting AI-driven energy management systems that dynamically adjust machine loads based on real-time renewable energy availability. Another trial involves mycelium-based packaging grown onsite using agricultural waste, potentially making both product and packaging carbon-negative. These manufacturing advances create tangible value for eco-conscious brands. Life cycle analyses show Yiwu Double-Tong's straws now have 73% lower carbon footprints than industry averages—a compelling selling point for global retailers facing Scope 3 emission targets.For businesses seeking truly sustainable straws from production to disposal, explore carbon-conscious options at https://www.sotonstraws.com/product/ .
    • Soit ça me demande de payer à travers paypal en envoyant "pour un proche" qui couvre aucun remboursement ou soit ça me dit de payer par CB mais ça me renvoie sur ramp network pour acheter de la crpyto J'ai essayé sur deux sites soit disant "KingTV365" et les deux c'est la même chose...
    • Quelqu'un sait ou s'abonner à King365TV svp ? Y a pleins de site, j'ai trouvé celui en .online mais pour payer via paypal faut envoyer "pour un proche" ça me parait louche
    • Pouvez-vous m'envoyer le tutoriel expliquant comment procéder ? Merci.
    • Il semblerait qu'ils aient maintenant changé le mot de passe et qu'il n'y ait plus aucun accès au routeur Huawei HG8145. Je ne peux même plus me connecter avec les informations par défaut. Je pense essayer l'accès UART au modem, car le contrôle qu'ils veulent devient agaçant.
×
×
  • Créer...