如何将ThreadPool.QueueUserWorkItem与非静态方法一起使用? [英] How to use ThreadPool.QueueUserWorkItem with non-static methods?

查看:109
本文介绍了如何将ThreadPool.QueueUserWorkItem与非静态方法一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试编译时,它会给我

When I try to compile it gives me

错误1非静态字段,方法或属性'ConsoleApplication1.Program.print(string)'ConsoleApplication1 \ ConsoleApplication1 \ Program.cs的对象引用是必需的15 47 ConsoleApplication1

Error 1 An object reference is required for the non-static field, method, or property 'ConsoleApplication1.Program.print(string)' ConsoleApplication1\ConsoleApplication1\Program.cs 15 47 ConsoleApplication1

因此,我将print标记为static,它可以工作.但是在更大的程序中,我有非静态方法.那么如何在这些方法中使用ThreadPool?

So, I marked print as static and it works. But in a bigger program I have non-static methods. So how do I use ThreadPool with those methods?

class Program
{
    static void Main(string[] args)
    {
        ThreadPool.QueueUserWorkItem(o => print("hello"));
        Console.ReadLine();
    }

    public void print(string s)
    {
        Console.WriteLine(s);
    }
}

推荐答案

您只需要一个实例即可对其进行操作:

You just need an instance to operate on:

var myObject = new WhateverClassItIs();
ThreadPool.QueueUserWorkitem(o => myObject.SomeMethod("some input"));

请记住,如果您使用的类型实现了IDisposable(或其他某种清除机制),则在确定异步操作已完成(或在异步操作结束时)之前,不应调用Dispose.操作本身).

Keep in mind that if the type that you use implements IDisposable (or some other cleanup mechanism), you should not invoke Dispose until you are certain that the asynchronous operation is completed (or at the end of the asynchronous operation itself).

这篇关于如何将ThreadPool.QueueUserWorkItem与非静态方法一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆