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 Chocolate Packaging Machine plays a vital role in advancing sustainable packaging within the confectionery industry. As consumer demand grows for eco-friendly products, manufacturers are seeking packaging solutions that reduce environmental impact without compromising chocolate quality or shelf life. Modern chocolate packaging machines enable the use of sustainable materials and efficient processes that align with green manufacturing goals. Why Is Sustainable Packaging Important? Sustainable packaging aims to minimize waste, reduce resource consumption, and enhance recyclability or biodegradability. It contributes to lowering carbon footprints and responding to consumer preferences for environmentally responsible products. How Do Chocolate Packaging Machines Facilitate Sustainability?   Aspect Sustainable Practice Benefits Material Compatibility Support for recyclable and biodegradable films Reduces plastic waste and landfill burden Precise Packaging Accurate dosing and sealing to minimize excess Less material use and food waste Energy Efficiency Machines designed to consume less power Decreases operational carbon emissions Waste Reduction Automated controls to reduce packaging defects Limits material discard during production What Packaging Materials Are Used? Chocolate packaging machines increasingly accommodate eco-friendly films such as compostable bioplastics, recycled paper laminates, and other sustainable composites that maintain product freshness while being kinder to the planet. How Does Automation Help? Automation optimizes material usage, reduces errors, and allows for quick changeovers to sustainable packaging formats, supporting flexible production without sacrificing efficiency. At Zjrctech, we are committed to providing advanced Chocolate Packaging Machines that support sustainable packaging initiatives. Our equipment is designed to integrate with eco-friendly materials and incorporate energy-saving technologies, helping your business meet environmental goals while delivering superior product protection. Learn more about our sustainable packaging solutions. Visit: http://zjrctech.com/
    • Training operators for efficient Twist Packaging Machine use is essential to maximize the machine’s performance, minimize downtime, and ensure product quality. Proper training empowers operators with the knowledge to handle the machine safely, troubleshoot minor issues, and maintain smooth operations. Why Is Operator Training Critical? Operators who understand machine mechanics and controls can prevent common errors that lead to packaging defects or equipment damage. Skilled operators also contribute to faster changeovers and better adherence to production schedules. Key Training Components   Training Aspect Description Benefits Machine Operation How to start, run, and stop the machine Safe and efficient daily use Troubleshooting Identifying and resolving common problems Reduces downtime Maintenance Routine cleaning and part replacement Extends machine lifespan Safety Procedures Guidelines to prevent accidents Ensures operator and equipment safety Quality Control Recognizing packaging defects Maintains product standards What Training Methods Work Best? Combining hands-on practice with detailed manuals and video tutorials helps operators learn effectively. Regular refresher courses and assessments keep skills up to date. How Does Training Impact Production? Well-trained operators improve throughput, reduce waste, and enhance the overall reliability of the packaging line, directly benefiting a company’s bottom line. At Zjrctech, we provide comprehensive training support for our Twist Packaging Machines to ensure clients achieve optimal performance and efficiency. Our expert team offers tailored training programs designed to meet your facility’s unique needs. Explore our advanced packaging solutions and training services. Visit: http://zjrctech.com/
    • Selecting the right material for shower drains is crucial for long-lasting performance, durability, and appearance. Stainless steel has become a preferred choice among Shower Drain China products due to its outstanding properties that meet the demands of modern bathrooms. Why Stainless Steel? Stainless steel offers superior corrosion resistance, essential in constantly wet environments like showers. Its resistance to rust and staining ensures that the drain maintains a clean, attractive look over time. Additionally, stainless steel’s strength and durability allow it to withstand heavy foot traffic and impacts. Key Advantages   Advantage Description Corrosion Resistance Stainless steel resists oxidation and chemical damage from water and cleaning agents. High Durability Strong material that maintains integrity under physical stress and daily use. Easy Maintenance Smooth surfaces prevent grime buildup and make cleaning easier, promoting hygiene. Aesthetic Appeal Polished or brushed finishes enhance the overall bathroom design. Eco-Friendly Stainless steel is recyclable, contributing to sustainable building practices. Enhanced Safety and Hygiene Stainless steel drains can be designed with anti-slip patterns and smooth finishes that discourage bacterial growth, helping maintain a clean and safe shower environment. Customization Opportunities Manufacturers in China offer OEM and ODM services, allowing customers to customize stainless steel shower drains in size, shape, and surface finish. This flexibility supports diverse project requirements and design preferences. Long-Term Value Though stainless steel shower drains may have a higher upfront cost than plastic alternatives, their longevity and minimal maintenance needs offer better overall value by reducing replacement frequency and associated labor costs. At Hasen-home, we pride ourselves on producing premium Shower Drain China products made from high-quality stainless steel. Our customizable solutions, combined with stringent quality control, ensure durability, elegance, and reliable performance tailored to your project. Choose Hasen-home for stainless steel shower drains that elevate both function and style. Learn more: https://www.hasen-home.com/news/shower-channle-drain-factory-zhejiang-hasen.html
    • Le VSOL V2802RH est en promotion,  gardez à l’esprit qu’avec cette route, vous devez sacrifier votre ligne téléphonique. prendre l’option 1pcs avec apc: https://fr.aliexpress.com/item/1005006334335891.html?spm=a2g0o.productlist.main.1.55d0QQWGQQWGRX&algo_pvid=f49e8289-83e8-4eb3-9183-7e8d9a8ef85a&algo_exp_id=f49e8289-83e8-4eb3-9183-7e8d9a8ef85a-0&pdp_ext_f={"order"%3A"31"%2C"eval"%3A"1"}&pdp_npi=4%40dis!EUR!41.76!20.46!!!343.71!168.42!%40211b653717514078910076309e983a!12000036797814661!sea!DZ!3439548271!X&curPageLogUid=c0bWTtHuAA0Q&utparam-url=scene%3Asearch|query_from%3A    
×
×
  • Créer...